Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

The greeting code in Java

2,055 views
Skip to first unread message

Saeed Amrollahi

unread,
Jun 19, 2011, 9:06:17 AM6/19/11
to
Dear all
Hi

I'm a C++ programmer and I started to learn Java. After famous "Hello
World"
program, the obvious code is "Say hello to specific people". Program
asked
user's name, then print a greeting message. The C++ code is:
#include <iostream>
#include <string>
Using std::cin; using std::cout; using std::string;
int main()
{
// ask for the person's name
std::cout << "Please enter your first name: ";
std::string name; // define name
std::cin >> name; // read into name
// write a greeting
std::cout << "Hello, " << name << "!" << std::endl;

return 0;
}
I tried to write the simplest code in Java and I ended up with the
following:

package Greeting;
import java.io.*;

public class Main {

public static void main(String[] args) throws IOException {
System.out.print("Please enter your first name: ");
String name = new String();
Reader r = new InputStreamReader(System.in);
for (char ch; (ch = (char)(r.read())) != '\n'; name += ch) {}
System.out.println("Hello, " + name);
}
}

What are the problems of my code and how can I write
a better one. Please throw some light.

TIA,
-- Saeed Amrollahi

Saeed Amrollahi

unread,
Jun 19, 2011, 9:05:53 AM6/19/11
to

Aéris

unread,
Jun 19, 2011, 9:19:58 AM6/19/11
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

public class Main {
public static void main(final String[] args) throws IOException {
final BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null && s.length() > 0) {


System.out.print("Please enter your first name:");

System.out.println("Hello, " + s);
}
}
}

- --
Aeris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJN/fd4AAoJEK8zQvxDY4P9/EgIAKlSeVV7UkYr8TAqLmwasN17
ftwzGWWpF6WhXmxq9Ow8T8T21Nwim6xSE9SpoHq/pHp8U1Apq0LgPMFTTyPaVjE3
ZQP+5ku+EyqTFBtrgTE5kB34TdmIDvMan7Um70j1hdppF6xCt8zWeojH5S4xSxD/
XxHNvXyji/WWn8fMbLcjs5Sma5bTkJr93OvScSkPLokBBX638HIkZLPJXx8H1Hqq
C8R91cw4yxCDUBL0JT8W/u4Nmc2pGj4I+BbwOCr3gDgTMbQx+Gtkf1UxVJ/Z/086
5z+VHp8mwrCDnaoS8G6fSV0npmodQ/shO5P3pp+VmfFHAJQWicMoF2znDuzy6xY=
=Ceb3
-----END PGP SIGNATURE-----

Saeed Amrollahi

unread,
Jun 19, 2011, 9:44:00 AM6/19/11
to
On Jun 19, 4:19 pm, Aéris <ae...@imirhil.fr> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> public class Main {
>         public static void main(final String[] args) throws IOException {
>                 final BufferedReader in = new BufferedReader(
>                         new InputStreamReader(System.in));
>                 String s;
>                 while ((s = in.readLine()) != null && s.length() > 0) {
>                         System.out.print("Please enter your first name:");
>                         System.out.println("Hello, " + s);
>                 }
>         }
>
> }
>
> - --
> Aeris

Thank you for your immediate answer. I ran your program and
it doesn't exactly did as the C++ version. First,
a message is printed and ask the user name, then the greeting
message is appeared on screen. In you program, no asking message
is appeared and the user can't figure out what should he/she do?
after username data entry we'll have the following output:
Aeris
Please enter your first name:Hello, Aeris
Also, please note In C++, the I/O operation using << and >>
are formatted, but in both code, we read the input, until
we reach the end of line.
You used the BufferedReader and InputStreamReader classes.
From point of educational view, do you think my code or your code
is as simple as the C++ version?

Regards,
-- Saeed

Jeff Higgins

unread,
Jun 19, 2011, 10:13:36 AM6/19/11
to
On 06/19/2011 09:44 AM, Saeed Amrollahi wrote:

> On Jun 19, 4:19 pm, A�ris<ae...@imirhil.fr> wrote:
>
> From point of educational view, do you think my code or your code
> is as simple as the C++ version?
>
What means simple?

Saeed Amrollahi

unread,
Jun 19, 2011, 10:17:41 AM6/19/11
to

Well, in the case of C++ code, I have to
explain cin, cout, string and two overloaded operators: >> and <<
in the case of java one: I have to
explain, the stream class hierarchy, InputStreamReader,
BufferedReader,
in, string, new operator, final, the meaning of buffered,
readLine, ...
I believe the C++ code is simpler for a beginner.

Regards,
-- Saeed

Jeff Higgins

unread,
Jun 19, 2011, 10:31:30 AM6/19/11
to
On 06/19/2011 09:06 AM, Saeed Amrollahi wrote:
>
> What are the problems of my code and how can I write
> a better one. Please throw some light.
What means better?

Aéris

unread,
Jun 19, 2011, 10:51:19 AM6/19/11
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Le 19/06/2011 15:44, Saeed Amrollahi a écrit :
> Thank you for your immediate answer. I ran your program and
> it doesn't exactly did as the C++ version. First,
> a message is printed and ask the user name, then the greeting
> message is appeared on screen. In you program, no asking message
> is appeared and the user can't figure out what should he/she do?

Yes, indeed, i did a mistake.
Replace the .print( with a .println(, othewise output is not flushed and
the greeting appear only after output.

> You used the BufferedReader and InputStreamReader classes.
> From point of educational view, do you think my code or your code
> is as simple as the C++ version?

Our C⁺⁺ version *seems* simplest, but concepts behind >> and << are very
complex and can be very dangerous (overriden operator).

And in your code, I don't no if you know the difference, but std::endl
is very very dangerous. It's not just equal to EOL but also flush the
buffer.
This bad shortcut lead to very poor i/o performances in most of
applications, all outputs flushing continuously buffer instead just send
EOL.

All of those considered, C⁺⁺ code is the shortest but not the simplest =)

- --
Aeris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJN/gziAAoJEK8zQvxDY4P9ChUH/0PevuUF1gmjz7VuPsc1+31L
3nNsrpg3TP343pz3jujbAhR8kKaTML44U/tX9TRtadGOfcfe1iurJv1FJ1qajmFn
nSXlDVSOB9QeI1RTZ0w5pkZt85jJxw3Mdun8K3c9XVfNts9pIVowgLJZ7kQNt/CO
y3RdMu0zq70DEFo8EEYuCfuo4F4OmdVQ0vk+EdFwo9vtBTgr6VPn2t+RLrOGZfUN
CZGOYYFwezH4+8WYiMOKEtHIS2fKIDE46bID957jbvo3qLRA6058bi5cPU6zyzXz
hdlzY59kdo/EstMG7Jo44qEpIqD0jzdgxUQVyZNWt7+8ghFnBOTcURlw/YiUa9k=
=You3
-----END PGP SIGNATURE-----

Jeff Higgins

unread,
Jun 19, 2011, 11:01:30 AM6/19/11
to
What language does the beginner wish to learn?


Stanimir Stamenkov

unread,
Jun 19, 2011, 11:06:23 AM6/19/11
to
Sun, 19 Jun 2011 16:51:19 +0200, /Aéris/:

> Yes, indeed, i did a mistake.
> Replace the .print( with a .println(, othewise output is not flushed and
> the greeting appear only after output.

No. Your code just prints the prompt after it has got the user input:

Sun, 19 Jun 2011 15:19:58 +0200, /Aéris/:

> public class Main {
> public static void main(final String[] args) throws IOException {
> final BufferedReader in = new BufferedReader(
> new InputStreamReader(System.in));
> String s;

> while ((s = in.readLine()) != null&& s.length()> 0) {


> System.out.print("Please enter your first name:");
> System.out.println("Hello, " + s);
> }
> }
> }

I guess one needs:

System.out.print("Please enter your first name: ");
while ((s = in.readLine()) != null && s.length() > 0) {

System.out.println("Hello, " + s);


System.out.print("Please enter your first name: ");
}

--
Stanimir

Aéris

unread,
Jun 19, 2011, 11:24:51 AM6/19/11
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Le 19/06/2011 17:06, Stanimir Stamenkov a écrit :
> I guess one needs:
>
> System.out.print("Please enter your first name: ");
> while ((s = in.readLine()) != null && s.length() > 0) {
> System.out.println("Hello, " + s);
> System.out.print("Please enter your first name: ");
> }
>

Shame on me…
My finger slipped on Eclipse…

- --
Aeris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJN/hS1AAoJEK8zQvxDY4P9exwIAI0b9L0AGvuShYg42ZoM2DIZ
th4n/50kzjjn58/nZRr/phFlLsigZqpYVhNzVZoBqYPFa12/IncxrgQsMJ4kEg/q
TdSr83nRkZ+wEXI1Q0KqMrcRiYWizEsrluMvt3VQLY1smuaQxZr9IyT5RbKTwyYE
pMEvfVakU2U8ntwsnzVcy8FN1UbqnD+HhezzHpSFDO4P5NsClJtquL7wxFCmaU4b
l0c7OJC8AlcnKHGnCESCifL5ecSC0Bf7wxt7t5u+Ks8J4/XylBZb8AdR8ChU6mo9
Qoh1upBKEH5yH4BhfK7ZkIzMCqdUy20qjnCg8kIrnb2/T/lCvvohfSiXdVnL6hg=
=YbyV
-----END PGP SIGNATURE-----

Jeff Higgins

unread,
Jun 19, 2011, 11:37:49 AM6/19/11
to
On 06/19/2011 11:24 AM, Aéris wrote:
> Le 19/06/2011 17:06, Stanimir Stamenkov a écrit :
>> I guess one needs:
>>
>> System.out.print("Please enter your first name: ");
>> while ((s = in.readLine()) != null&& s.length()> 0) {

>> System.out.println("Hello, " + s);
>> System.out.print("Please enter your first name: ");
>> }
>>
>
> Shame on me…
> My finger slipped on Eclipse…
>
The original example didn't loop.

BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
StringBuilder builder = new StringBuilder("Hello, ");


System.out.print("Please enter your first name: ");

try {
builder.append(reader.readLine());
builder.append("!");
System.out.println(builder);
} catch (IOException e) {
System.err.println("Something's wrong, a stack trace follows:");
e.printStackTrace();
}

Jeff Higgins

unread,
Jun 19, 2011, 11:40:26 AM6/19/11
to
On 06/19/2011 11:24 AM, Aéris wrote:
>
> Shame on me…
> My finger slipped on Eclipse…
>
Pretty, slick, Eclipse. :)
Message has been deleted

Jeff Higgins

unread,
Jun 19, 2011, 12:08:36 PM6/19/11
to
On 06/19/2011 11:36 AM, Stefan Ram wrote:
> Jeff Higgins<je...@invalid.invalid> writes:
>> What means simple?
>
> 10 INPUT "Please enter your first name: "; N$
> 20 PRINT "Hello, "; N$; "!"
> 30 END
>
I acquired my first PC at a yard sale in 1984.
It was an SBC 2000: monitor, single 5" floppy,
and keyboard all in one case.
I spent many enjoyable hours on that machine.

Stanimir Stamenkov

unread,
Jun 19, 2011, 12:07:10 PM6/19/11
to
Sun, 19 Jun 2011 06:06:17 -0700 (PDT), /Saeed Amrollahi/:

> public static void main(String[] args) throws IOException {
> System.out.print("Please enter your first name: ");
> String name = new String();
> Reader r = new InputStreamReader(System.in);
> for (char ch; (ch = (char)(r.read())) != '\n'; name += ch) {}
> System.out.println("Hello, " + name);
> }
>
> What are the problems of my code and how can I write
> a better one. Please throw some light.

You don't need to initialize 'name' with a 'new String()' - just
assign it with an empty string literal which is a constant:

String name = "";

The 'name += ch' will assign it a new String instance, also. In
this regard you may better use a StringBuilder:

StringBuilder name = new StringBuilder();


Reader r = new InputStreamReader(System.in);

int ch = r.read();
while (ch != -1 && ch != '\n') {
name.append((char) ch);
ch = r.read();
}
System.out.println("Hello, " + name);

In the above snippet I also check whether the Reader is returning
-1, which would mean 'System.in' has been closed for some reason -
otherwise you risk going in infinite loop, in that case.

--
Stanimir

rossum

unread,
Jun 19, 2011, 12:36:36 PM6/19/11
to

Stream readers are more often used for binary input. For text input
people tend to use the java.util.Scanner class.

public static void main(String[] args) {


System.out.print("Please enter your first name: ");

Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("Hello, " + name);
}

rossum

Message has been deleted

Jeff Higgins

unread,
Jun 19, 2011, 1:07:08 PM6/19/11
to
On 06/19/2011 09:06 AM, Saeed Amrollahi wrote:
>
> package Greeting;
> import java.io.*;
>
> public class Main {
>
> public static void main(String[] args) throws IOException {
> System.out.print("Please enter your first name: ");
> String name = new String();
> Reader r = new InputStreamReader(System.in);
> for (char ch; (ch = (char)(r.read())) != '\n'; name += ch) {}
> System.out.println("Hello, " + name);
> }
> }
>
> What are the problems of my code and how can I write
> a better one. Please throw some light.
>
besides what others have mentioned, the condition

(ch = (char)(r.read())) != '\n'
introduces a platform dependence.

Jeff Higgins

unread,
Jun 19, 2011, 1:11:18 PM6/19/11
to
On 06/19/2011 01:07 PM, Jeff Higgins wrote:
There is also java.io.Console
<http://download.oracle.com/javase/6/docs/api/java/io/Console.html>


Jeff Higgins

unread,
Jun 19, 2011, 2:19:36 PM6/19/11
to
public class Main {
public static void main(String[] args) {
System.console().printf("Hello, %1$s!\n",
System.console().readLine("Please enter your first name: "));
}
}

Saeed Amrollahi

unread,
Jun 19, 2011, 2:36:59 PM6/19/11
to

For example using less abstractions and less involve with Java
stream class hierarchy.
-- Saeed

Jeff Higgins

unread,
Jun 19, 2011, 3:03:24 PM6/19/11
to

For a beginner, learning to write C in Java is unhelpful.


Saeed Amrollahi

unread,
Jun 19, 2011, 3:05:00 PM6/19/11
to
On Jun 19, 6:51 pm, Aéris <ae...@imirhil.fr> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Le 19/06/2011 15:44, Saeed Amrollahi a écrit :
>
> > Thank you for your immediate answer. I ran your program and
> > it doesn't exactly did as the C++ version. First,
> > a message is printed and ask the user name, then the greeting
> > message is appeared on screen. In you program, no asking message
> > is appeared and the user can't figure out what should he/she do?
>
> Yes, indeed, i did a mistake.
> Replace the .print( with a .println(, othewise output is not flushed and
> the greeting appear only after output.
>
Now it OK.

> > You used the BufferedReader and InputStreamReader classes.
> > From point of educational view, do you think my code or your code
> > is as simple as the C++ version?
>
> Our C⁺⁺ version *seems* simplest, but concepts behind >> and << are very
> complex and can be very dangerous (overriden operator).
>
As you said, may be the concepts behind them are complex (I don't
agree
with you), but their usage is really simple.

> And in your code, I don't no if you know the difference, but std::endl
> is very very dangerous. It's not just equal to EOL but also flush the
> buffer.
It's not dangerous. but my answer: use '\n' rather than std::endl;

> This bad shortcut lead to very poor i/o performances in most of
> applications, all outputs flushing continuously buffer instead just send
> EOL.
>
> All of those considered, C⁺⁺ code is the shortest but not the simplest =)
>
BTW, thank you for your insightful answers.

> - --
> Aeris
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.11 (GNU/Linux)
> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org/

Saeed Amrollahi

unread,
Jun 19, 2011, 3:08:33 PM6/19/11
to
On Jun 19, 8:07 pm, Stanimir Stamenkov <s7a...@netscape.net> wrote:
> Sun, 19 Jun 2011 06:06:17 -0700 (PDT), /Saeed Amrollahi/:
>
> >      public static void main(String[] args) throws IOException {
> >          System.out.print("Please enter your first name: ");
> >          String name = new String();
> >          Reader r = new InputStreamReader(System.in);
> >          for (char ch; (ch = (char)(r.read())) != '\n'; name += ch) {}
> >          System.out.println("Hello, " + name);
> >      }
>
> > What are the problems of my code and how can I write
> > a better one. Please throw some light.
>
> You don't need to initialize 'name' with a 'new String()' - just
> assign it with an empty string literal which is a constant:
>
>          String name = "";
>
You are right.

Saeed Amrollahi

unread,
Jun 19, 2011, 3:15:01 PM6/19/11
to

What is the Scanner? Why we use nextLine? What's the relation of
such concepts with a simple greeting program.
Why the code for writing "Hello, world" is in chapter 1, page 1
of The Java Programming Language, but the code of greeting may be in
Chapter 20!
-- Saeed
for

Saeed Amrollahi

unread,
Jun 19, 2011, 3:06:44 PM6/19/11
to

Actually, I am going to prepare a seminar under the title: C++ vs.
Java
I try to compare C++ and Java from point of programming view.

Martin Gregorie

unread,
Jun 19, 2011, 3:46:37 PM6/19/11
to
On Sun, 19 Jun 2011 12:15:01 -0700, Saeed Amrollahi wrote:

> What is the Scanner? Why we use nextLine? What's the relation of such
> concepts with a simple greeting program. Why the code for writing
> "Hello, world" is in chapter 1, page 1 of The Java Programming Language,
> but the code of greeting may be in Chapter 20!

It sounds as though you didn't download and install the Java SE
documentation package. You need it: the Java equivalent of the C standard
library is considerably bigger and is fully documented there via the
Javadocs documentation tool, which is also part of the standard JDK.
C/C++ doesn't have a standard documentation tool that comes near
Javadocs.

The Java 6 standard class library includes the Scanner class, so of
course it is fully described in the Java 6 documentation set. The
description there is much better than any summary we might write. Quite
apart from anything else, you'll find that writing your comparison is a
lot easier if you have the documentation set installed and use it to help
your writing.


--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |

Joshua Cranmer

unread,
Jun 19, 2011, 4:00:21 PM6/19/11
to
On 06/19/2011 03:15 PM, Saeed Amrollahi wrote:
> What is the Scanner? Why we use nextLine? What's the relation of
> such concepts with a simple greeting program.

java.util.Scanner is a very useful class for parsing simple textual
protocols, that makes retrieval of words, lines, numbers, etc. very
simple. In other words, it's very much like istream::operator<< except
more explicit in what it is doing (does operator<<(string&) feed me a
word or a line?); that Java did not have it until version 5 is a great
shame.

> Why the code for writing "Hello, world" is in chapter 1, page 1
> of The Java Programming Language, but the code of greeting may be in
> Chapter 20!

Outputting ASCII is very simple, and "Hello, world" has become (for
better or for worse) the standard introduction to programming. True I/O,
one that takes into account the harsh vagaries of international text and
the heaping mess that is character sets, is actually very difficult and
very easy to get wrong. Reading from an input stream is actually
logically difficult (what happens if you read from a closed stdin?);
Java 1.0 actually got this mildly wrong, which is part of the reason why
the APIs for particularly reading Strings is much more circuitous.

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth

Eric Sosman

unread,
Jun 19, 2011, 4:05:23 PM6/19/11
to
On 6/19/2011 3:15 PM, Saeed Amrollahi wrote:
> [...]

> What is the Scanner? Why we use nextLine? What's the relation of
> such concepts with a simple greeting program.

The Scanner class and its nextLine method are part of an I/O
library that offers more power and flexibility than your program is
capable of using.

Unfortunately for you, the designers of Java chose not to
provide a built-in I/O facility dumbed down to the level you need.
You're not using a tenth of the power of Scanner, but that would
be a poor reason for Scanner to jettison its other nine-tenths.

> Why the code for writing "Hello, world" is in chapter 1, page 1
> of The Java Programming Language, but the code of greeting may be in
> Chapter 20!

Permute the chapter numbers if it makes you happier. For example,
you don't need to know how to write constructors, you don't need to
understand the `long' type, you don't need to know about nested classes,
and so on, and so on. Move chapter 20 ahead of all those, if you like.

More seriously, the purpose of a "Hello, world" program is not
to teach you the language (whatever language) nor to illustrate its
capabilities. It is a throat-clearing exercise intended to test
whether the compiler/interpreter/libraries/runtime/licenses/whatnot
are set up correctly. "Testing, testing, one, two, three" is not
intended to convey a message, but to check that everything from the
microphone to the speaker is properly connected and powered on. Do
not judge the PA system by the banality of its first message.

I imagine you are a C++ practitioner trying to learn Java, but
making the mistake of trying to understand Java in C++'s terms. Have
you ever hear the phrase "A real programmer can write FORTRAN in any
language?" Try not to commit that error, but instead look at Java on
its own merits (and its own demerits; Java's not perfect).

Bruce Eckel's "Thinking in Java" gets a lukewarm reception (at
best) from the experts, and I don't know whether it's been kept up
to date as Java has developed and changed. However, it has one virtue
I found helpful Back In The Day, and you may find helpful now: True to
its title, it really does try to explain Java in Java's own terms, and
not by saying "It's just like Lisp except ..." A goodly dose of that
mindset might stand you in good stead.

--
Eric Sosman
eso...@ieee-dot-org.invalid

Aéris

unread,
Jun 19, 2011, 4:06:37 PM6/19/11
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Le 19/06/2011 21:06, Saeed Amrollahi a �crit :


> I try to compare C++ and Java from point of programming view.

In this case, do not just compare language each others, but also related
tools.

Maven or Graddle are must have in the Java World, or other tools like
Jenkins, Sonar?

Java is not just a language, it's a World. It most important part is
also community and tools.

- --
Aeris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJN/lbIAAoJEK8zQvxDY4P9kyAH/002cDmNtahTv9VsSw0V7W3T
OzUTF9QGHZuuhjiO0dpfStgt0CsQsr+LdueRL1yqDxSBFlMjunvAoF3/2J1fQ10j
LdZkpQ1zYP9X5DXmuzMFmYILhtwCX2Q9HS2Mt+igs2zVrhDyQvSP2wArfxKxTsSD
XTrQ1j+pgMuOuVejxHOr6/oWeLjhCDKV4taMcm+F9uwp5Ze7q2T5ZnOi6tF5sMvB
9WYemCtfni2TPDtmklqwyPMBsMmzUJT10G23unlmXGxmh33XMglxEkgNltQk11AF
acceSLsNI9YMeTvvEkejCxae1Ok57nruEPl2jkWrAagjc5/OxEW3rLjXLxc+m18=
=sq/+
-----END PGP SIGNATURE-----

Message has been deleted

Joshua Cranmer

unread,
Jun 19, 2011, 4:25:54 PM6/19/11
to
On 06/19/2011 10:17 AM, Saeed Amrollahi wrote:
> Well, in the case of C++ code, I have to
> explain cin, cout, string and two overloaded operators:>> and<<
> in the case of java one: I have to
> explain, the stream class hierarchy, InputStreamReader,
> BufferedReader,
> in, string, new operator, final, the meaning of buffered,
> readLine, ...

If that is what you're explaining in Java, you also need to explain for
C++ stack constructed-objects, references, #include (trust me, beginners
can get very confused about #include, as simple as it looks), and
probably the entire iostream interfaces if you're talking about Java's
stream class hierarchy.

> I believe the C++ code is simpler for a beginner.

If it's simpler, it's only superficially so. C++'s interfaces heavily
optimize for the most common case and render the development of the more
critical components inordinately more difficult. For example, a fair
amount of my work has to worry about the use of international characters
and multiple charsets (it's not unimaginable that I have to use one
stream to write in two simultaneous charsets (i.e., the control protocol
is in UTF-8 but I send 8-bit MIME payloads of ISO 8859-1)). In Java, I
can keep both the raw Stream and a controlling Reader/Writer around and
use the character-based one for control information and the octet-based
one for data payloads.

And, naturally, any talk of C++ being simpler becomes hard to stomach
once you introduce templates, i.e., any use of the STL. std::string
isn't actually a class, it's actually std::basic_string<char,
std::char_traits<char>, std::allocator<char> >, as every error message
involving std::set<std::string> will helpfully inform you. I mean
std::set<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::less<std::basic_string<char,
std::char_traits<char>, std::allocator<char> > >,
std::allocator<std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >. Have fun debugging your template errors!

Message has been deleted

Joshua Cranmer

unread,
Jun 19, 2011, 5:22:35 PM6/19/11
to
On 06/19/2011 04:53 PM, Stefan Ram wrote:
> The new C++ standard has more than 1300 pages, but this is
> base on the C standard with more than 500 pages. These are
> nearly 1900 pages of a text in a condensed technical
> language, yet the language does not allow to access a
> directory of the filesystem or a socket of the network.

In all fairness, the first 200 pages or so of the C standard are
language semantics, which C++ redefines for itself anyways. It's the
library and a few of the annexes that are important for C++ (so about
300 pages, give or take). Of course, you might want to add for some more
information specs like IEEE 754 (~70 pages) if you want to know more
information about floating points.

The JLS itself is 684 pages, compared to the ~450 pages that C++ takes
to explain its language. The C++0x library takes around 800 pages to
explain the rough equivalent to large hunks of java.lang and java.util.

On the other hand, the JLS is a lot more explicit and burns through
space with examples, so it is relatively low in information density for
a specification. The standard Java API is also probably the best example
of API documentation in widespread usage.

Message has been deleted

rossum

unread,
Jun 19, 2011, 5:28:23 PM6/19/11
to
On Sun, 19 Jun 2011 12:15:01 -0700 (PDT), Saeed Amrollahi
<amrolla...@gmail.com> wrote:

>What is the Scanner?
As Martin said, you need to read the Javadoc:
(http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html)

Java is a relatively small language with a huge standard library. You
cannot understand the language without knowing the basics of the
library. The library is described in the Javadocs. If you have not
done so already, download them from
(http://www.oracle.com/technetwork/java/javase/downloads/index.html#docs)
and install them on your computer. Your IDE should be able to link to
them and use them to help you.

>Why we use nextLine?
It returns the next line of input as a String. Since your program
reads a line of input it is the obvious method to use.

>What's the relation of
>such concepts with a simple greeting program.
>Why the code for writing "Hello, world" is in chapter 1, page 1
>of The Java Programming Language, but the code of greeting may be in
>Chapter 20!

Ask the authour of the book you are using.

rossum

> -- Saeed


Nasser M. Abbasi

unread,
Jun 19, 2011, 10:35:53 PM6/19/11
to
On 6/19/2011 8:36 AM, Stefan Ram wrote:
> Jeff Higgins<je...@invalid.invalid> writes:
>> What means simple?
>
> 10 INPUT "Please enter your first name: "; N$
> 20 PRINT "Hello, "; N$; "!"
> 30 END
>


Ok, I will join the fun:


Mathematica:

------------------
name = InputString["Name?"]
Print["Hello "<>name];
-----------------

Matlab:

-------------------------------
name = input('Name?','s')
fprintf('hello %s\n',name)
--------------------------

--Nasser

Message has been deleted

Roedy Green

unread,
Jun 20, 2011, 12:14:18 AM6/20/11
to
On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
<amrolla...@gmail.com> wrote, quoted or indirectly quoted someone
who said :

>What are the problems of my code and how can I write
>a better one. Please throw some light.

see http://mindprod.com/applet/fileio.html
to get it to generate code for various purposes.

You can read a line at a time and save yourself a fair bit of
complication.
--
Roedy Green Canadian Mind Products
http://mindprod.com
One of the great annoyances in programming derives from the irregularity
of English spelling especially when you have international teams.
I want to find a method or variable, but I don't know precisely
how its is spelled or worded. English is only approximately phonetic.
Letters are randomly doubled. The dictionary often lists variant spellings.
British, Canadian and American spellings differ.I would like to see an
experiment where variable names were spelled in a simplified English, where
there were no double letters.I also think you could add a number of rules
about composing variable names so that a variable name for something would
be highly predictable. You would also need automated enforcement of the
rules as well as possible.

Roedy Green

unread,
Jun 20, 2011, 12:23:28 AM6/20/11
to
On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
<amrolla...@gmail.com> wrote, quoted or indirectly quoted someone
who said :

>package Greeting;


>import java.io.*;
>
>public class Main {

packages are traditionally all lower case. e.g. "greeting".

Further they should be globally unique by including your domain name,
e.g. "com.amrollahi.saeed.greeting". That way you can share code with
others without worrying about package name clashes.

Main is not a very descriptive name for a class. Try "Greeting".

The code itself works fine, though it is a "vortope" translation of C
rather than idiomatic Java. You forgot to close your stream.

An fairly easy extension is a while EOFException loop to handle more
than one name.

Thank you for compiling and running your code before asking help. So
many newbies fail to do that. You also explained what your code was
supposed to do. These are lessons that seem almost impossible to get
into newbie heads.

Nasser M. Abbasi

unread,
Jun 20, 2011, 12:41:11 AM6/20/11
to
On 6/19/2011 9:05 PM, Stefan Ram wrote:

> "Nasser M. Abbasi"<n...@12000.org> writes:
>> name = InputString["Name?"]
>> Print["Hello "<>name];
>
> ... and to do this in JEE, just follow precisely these
> 50 pages:
>
> http://download.oracle.com/javaee/6/firstcup/doc/firstcup.pdf
>
> (Ok, actually it reads the birthday date of the user and
> then outputs two lines of info about the age of the user,
> but this is still similar in spirit to the above program.)
>

Well, I guess the above is a good example of why you Java
programmers get the big bucks !

--Nasser

Joshua Cranmer

unread,
Jun 20, 2011, 1:02:15 AM6/20/11
to
On 06/19/2011 11:36 AM, Stefan Ram wrote:
> Jeff Higgins<je...@invalid.invalid> writes:
>> What means simple?
>
> 10 INPUT "Please enter your first name: "; N$
> 20 PRINT "Hello, "; N$; "!"
> 30 END

In the hq9ni language, it's even easier:

i

Saeed Amrollahi

unread,
Jun 20, 2011, 1:34:43 AM6/20/11
to
On Jun 19, 10:46 pm, Martin Gregorie <mar...@address-in-sig.invalid>
wrote:

I'll download it and use it.
-- Saeed Amrollahi

Saeed Amrollahi

unread,
Jun 20, 2011, 1:33:13 AM6/20/11
to
On Jun 19, 11:06 pm, Aéris <ae...@imirhil.fr> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Le 19/06/2011 21:06, Saeed Amrollahi a écrit :
>
> > I try to compare C++ and Java from point of programming view.
>
> In this case, do not just compare language each others, but also related
> tools.
>
> Maven or Graddle are must have in the Java World, or other tools like
> Jenkins, Sonar?
>
> Java is not just a language, it's a World. It most important part is
> also community and tools.
>
Actually C++ is just a language not a complete system.
Java is a complete system not just a language.
For this reason, in Java we have to mention the name tools,
BTW, thank you for the name of some tools, except Maven I hadn't
hear about others.
-- Saeed Amrollahi

> - --
> Aeris
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.11 (GNU/Linux)
> Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org/
Message has been deleted

Saeed Amrollahi

unread,
Jun 20, 2011, 1:40:25 AM6/20/11
to
Of course I don't do that. Each programming language has its own
terminology,
culture, ideals, idioms and styles.
-- Saeed Amrollahi
> --
> Eric Sosman
> esos...@ieee-dot-org.invalid

Martin Gregorie

unread,
Jun 20, 2011, 6:13:04 AM6/20/11
to
On Sun, 19 Jun 2011 20:24:13 +0000, Stefan Ram wrote:

> Martin Gregorie <mar...@address-in-sig.invalid> writes:
>>C/C++ doesn't have a standard documentation tool that comes near
>>Javadocs.
>

> Classical C was part of UNIX, and its »standard documentation tool«
> was »(n|g)roff -man«/»man«.
>
Indeed - and this is not exactly or portable (as you said) and rarely
found outside the *NIX world.

IMO the main advantage of Javadocs over virtually all the other program
documentation tools is that it can generate documentation from a program
source that follows the conventions and requires a minimum of of
documentary annotation. Compare that with the requirement that C
documentation must be a separately maintained (n|g)roff text file that
can be almost unreadable in raw form, though the latest versions of less
do remove a lot of the formatting and checking nausea.

However, less, like (g|n)roff is also almost unknown outside the *NIX
world.

> However, it has not been man portable together with C
>
Indeed - text editors are everywhere but the same can't be said about
(n|g)roff.

I ended up writing my own Javadocs knock-off for C (cdoc) that can
generate HTML that approximates a cross between Javadocs indexing/
pagination and the usual C library documentation format. It can do a
reasonable job of documenting unmodified C source provided only that it
has a heading comment for the C source file and a preceding comment for
each function.

Its also highly portable, since I wrote it in Java.

RedGrittyBrick

unread,
Jun 20, 2011, 11:36:56 AM6/20/11
to
On 19/06/2011 20:06, Saeed Amrollahi wrote:
> I am going to prepare a seminar under the title: C++ vs.
> Java
> I try to compare C++ and Java from point of programming view.

Most people don't write "Hello" programs, so comparing languages by
counting lines of source code for "Hello" - doesn't really tell you much.

perl -e 'print "Hello $ARGV[0]\n"' Fred
Hello Fred

ksh -c 'print Hello $0' Fred
Hello Fred

I hope you would not think it relevant to conclude that Goldman Sachs,
Microsoft and Notch writing share-trading systems, word processors and
video-games will find it easier to learn Korn shell and not Java, C or C++?

--
RGB

Jeff Higgins

unread,
Jun 20, 2011, 12:25:05 PM6/20/11
to

You seem sincere but I can't help wonder:
Who is the intended audience? What is the goal?
Hopefully it's not a usenet seminar posted to both
C++ and Java groups. That's been done, and is a messy format.

Jeff Higgins

unread,
Jun 20, 2011, 1:00:57 PM6/20/11
to
On 06/20/2011 12:25 PM, Jeff Higgins wrote:

> You seem sincere but I can't help wonder:
> Who is the intended audience? What is the goal?

I can almost see a serial type format:

Java: Accounts of My Explorations.
1. Hello
2. Crossing Streams
3. Buildings
...


Jeff Higgins

unread,
Jun 20, 2011, 3:24:05 PM6/20/11
to
On 06/20/2011 01:00 PM, Jeff Higgins wrote:

> Java: Accounts of My Explorations.
> 1. Hello

... The maddening rattle-clank of the trucks on rails subsided as our
train approached Java Station. Outside the dusty, smokey panes of the
stifling car, amid the lush forest of Java, suddenly loomed a great line
of platforms. On and on they seemed to stretch, each different and I
hadn't been informed where to disembark. I reached for my preprocessor;
but the brown-eyed girl, sensing my anxiety, smiled and touched my hand.
"They are all the same" she whispered, "write once, run anywhere, we say
here". Pulling the signalling cord, she said "Come along, we'll get off
here and I'll show you." "We shall say hello and they will all
understand us, and smile and welcome us."
...

blmblm.m...@gmail.com

unread,
Jun 20, 2011, 3:20:45 PM6/20/11
to
In article <f61fee62-589e-4ad1...@s9g2000yqm.googlegroups.com>,
Saeed Amrollahi <amrolla...@gmail.com> wrote:
>
> Dear all
> Hi
>
> I'm a C++ programmer and I started to learn Java. After famous "Hello
> World"
> program, the obvious code is "Say hello to specific people". Program
> asked
> user's name, then print a greeting message. The C++ code is:
> #include <iostream>
> #include <string>
> Using std::cin; using std::cout; using std::string;
> int main()
> {
> // ask for the person's name
> std::cout << "Please enter your first name: ";
> std::string name; // define name
> std::cin >> name; // read into name
> // write a greeting
> std::cout << "Hello, " << name << "!" << std::endl;
>
> return 0;
> }
> I tried to write the simplest code in Java and I ended up with the
> following:

>
> package Greeting;
> import java.io.*;
>
> public class Main {
>
> public static void main(String[] args) throws IOException {
> System.out.print("Please enter your first name: ");
> String name = new String();
> Reader r = new InputStreamReader(System.in);
> for (char ch; (ch = (char)(r.read())) != '\n'; name += ch) {}
> System.out.println("Hello, " + name);
> }
> }

Um, has anyone else pointed out that these two programs don't do the
same thing? Unless the C++ implemented by GCC is broken, the C++
program reads a whitespace-delimited string, while the Java program
reads a full line of text.

Just sayin'. (I agree by the way with most of the other comments
about there being much better ways to accomplish -- well, whatever it
is you're trying to accomplish, given that the two programs seem to
me to be doing slightly different things.)

--
B. L. Massingill
ObDisclaimer: I don't speak for my employers; they return the favor.

blmblm.m...@gmail.com

unread,
Jun 20, 2011, 3:21:37 PM6/20/11
to
In article <4dfe0ce7$0$4853$426a...@news.free.fr>,

Aéris <ae...@imirhil.fr> wrote:
>
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Le 19/06/2011 15:44, Saeed Amrollahi a �crit :

[ snip ]

> And in your code, I don't no if you know the difference, but std::endl
> is very very dangerous. It's not just equal to EOL but also flush the
> buffer.
> This bad shortcut lead to very poor i/o performances in most of
> applications, all outputs flushing continuously buffer instead just send
> EOL.

Huh. There's actually an explicit "flush" in the implementation?
Interesting. How did you find this out? I'm not a C++ expert but
had not come across a mention of this detail.

Of course, if writing prompts to stdout with the implicit assumption
that the program is being run interactively, flushing the buffer is
what one wants.

Just sayin'.

blmblm.m...@gmail.com

unread,
Jun 20, 2011, 3:22:50 PM6/20/11
to
In article <itlgsn$vr8$1...@dont-email.me>,
Jeff Higgins <je...@invalid.invalid> wrote:
>
> On 06/19/2011 02:36 PM, Saeed Amrollahi wrote:
> > On Jun 19, 6:31 pm, Jeff Higgins<j...@invalid.invalid> wrote:

> >> On 06/19/2011 09:06 AM, Saeed Amrollahi wrote:
> >>
> >>> What are the problems of my code and how can I write
> >>> a better one. Please throw some light.
> >>
> >> What means better?
> >
> > For example using less abstractions and less involve with Java
> > stream class hierarchy.
>
> For a beginner, learning to write C in Java is unhelpful.

Even in C one would not be likely to input a string by reading one
charaacter at a time -- in a beginner program at least.

blmblm.m...@gmail.com

unread,
Jun 20, 2011, 3:23:24 PM6/20/11
to
In article <45250777-03f2-4391...@c20g2000vbv.googlegroups.com>,
Saeed Amrollahi <amrolla...@gmail.com> wrote:

>
> On Jun 19, 7:01 pm, Jeff Higgins <j...@invalid.invalid> wrote:
> > On 06/19/2011 10:17 AM, Saeed Amrollahi wrote:

[ snip ]

> Actually, I am going to prepare a seminar under the title: C++ vs.
> Java
> I try to compare C++ and Java from point of programming view.

All the more reason to try for examples that make idiomatic use
of language features, then. Your C++ program doesn't read its input
a character at a time; why should the Java program?

Tobias Blass

unread,
Jun 21, 2011, 3:44:38 AM6/21/11
to
On 2011-06-20, blmblm myrealbox.com <blmblm.m...@gmail.com> wrote:
> In article <itlgsn$vr8$1...@dont-email.me>,
> Jeff Higgins <je...@invalid.invalid> wrote:
>>
>> On 06/19/2011 02:36 PM, Saeed Amrollahi wrote:
>> > On Jun 19, 6:31 pm, Jeff Higgins<j...@invalid.invalid> wrote:
>> >> On 06/19/2011 09:06 AM, Saeed Amrollahi wrote:
>> >>
>> >>> What are the problems of my code and how can I write
>> >>> a better one. Please throw some light.
>> >>
>> >> What means better?
>> >
>> > For example using less abstractions and less involve with Java
>> > stream class hierarchy.
>>
>> For a beginner, learning to write C in Java is unhelpful.
>
> Even in C one would not be likely to input a string by reading one
> charaacter at a time -- in a beginner program at least.
>

Hmm at least in K&R (the inofficial standard C learning book) you often find
while((c=getchar())!=EOF)

It's less performant than reading whole blocks but in many cases much simpler
(And that's what matters in a learning book)

Message has been deleted

Tobias Blass

unread,
Jun 21, 2011, 5:34:34 AM6/21/11
to
On 2011-06-21, Stefan Ram <r...@zedat.fu-berlin.de> wrote:

> Tobias Blass <tobia...@gmx.net> writes:
>>Hmm at least in K&R (the inofficial standard C learning book) you often find
>>while((c=getchar())!=EOF)
>>It's less performant than reading whole blocks but in many cases much simpler
>>(And that's what matters in a learning book)
>
> Usually, »getchar« already is buffered internally.
>
> (Also, thinking about optimising even before any
> requirement specification is given really seems
> to be premature.)
>
> [snip some quotes]
>
> M. A. Jackson
>

I know these quotes (every programmer should).
I didn't want to warn of using getchar. I must admit the performance thing was a
guess (and I think I read it somewhere), but even if it is the second part of
the sentence applies. Premature Optimization is mainly evil _because_ you
sacrifice simplicity (there are other reasons but this is the most important
one).

Gene Wirchenko

unread,
Jun 21, 2011, 10:47:06 AM6/21/11
to
On Tue, 21 Jun 2011 09:34:34 +0000 (UTC), Tobias Blass
<tobia...@gmx.net> wrote:

[snip]

>I know these quotes (every programmer should).
>I didn't want to warn of using getchar. I must admit the performance thing was a
>guess (and I think I read it somewhere), but even if it is the second part of
>the sentence applies. Premature Optimization is mainly evil _because_ you
>sacrifice simplicity (there are other reasons but this is the most important
>one).

This point was covered neatly in "Code Complete". At least, it
was in the first edition. I have not read the latest.

McConnell was writing encryption software to run on an original
IBM pc. He optimised and optimised to speed up his C code. Finally,
he hucked it and rewrote in Assembler. His observation was that as
more and more optimisations were added, the code became much less
readable.

I like to optimise for code readability. If code is useful, it
generally will have a long lifetime. That gives more opportunity for
changes being required. Changes are a real bother when the code is
not easily readable.

Sincerely,

Gene Wirchenko

blmblm.m...@gmail.com

unread,
Jun 21, 2011, 4:43:12 PM6/21/11
to
In article <itpi56$9du$1...@dont-email.me>,

Tobias Blass <tobia...@gmx.net> wrote:
> On 2011-06-20, blmblm myrealbox.com <blmblm.m...@gmail.com> wrote:
> > In article <itlgsn$vr8$1...@dont-email.me>,
> > Jeff Higgins <je...@invalid.invalid> wrote:
> >>
> >> On 06/19/2011 02:36 PM, Saeed Amrollahi wrote:
> >> > On Jun 19, 6:31 pm, Jeff Higgins<j...@invalid.invalid> wrote:
> >> >> On 06/19/2011 09:06 AM, Saeed Amrollahi wrote:
> >> >>
> >> >>> What are the problems of my code and how can I write
> >> >>> a better one. Please throw some light.
> >> >>
> >> >> What means better?
> >> >
> >> > For example using less abstractions and less involve with Java
> >> > stream class hierarchy.
> >>
> >> For a beginner, learning to write C in Java is unhelpful.
> >
> > Even in C one would not be likely to input a string by reading one
> > charaacter at a time -- in a beginner program at least.

s/charaacter/character/, of course (why do these details only become
apparently *after* posting?)

> Hmm at least in K&R (the inofficial standard C learning book) you often find
> while((c=getchar())!=EOF)
>
> It's less performant than reading whole blocks but in many cases much simpler
> (And that's what matters in a learning book)

Well, if you say so (my copy of K&R is not easily accessed right
now). Certainly that style makes sense in examples in which
the goal is to process a character at a time (to classify/count
characters, for example, or to copy one file to another).

But is this style used in examples in which the objective is to
collect one whitespace-delimited "string" and print it? Huh.
Maybe I need to reread K&R ....

Tobias Blass

unread,
Jun 22, 2011, 4:35:00 AM6/22/11
to

Obviously it is not the right choice for any problem you might encounter (the
K&R examples are copy input to output, count characters, count lines etc.) but
there are situations where getchar() is useful and one should be aware that
it exists. I don't want to say that one should use it everywhere.

Michael Wojcik

unread,
Jun 22, 2011, 9:29:38 AM6/22/11
to
Martin Gregorie wrote:
>
> IMO the main advantage of Javadocs over virtually all the other program
> documentation tools

Where "virtually all" apparently means "except for all of the many
other tools that do this".

> is that it can generate documentation from a program
> source that follows the conventions and requires a minimum of of
> documentary annotation.

The technique of annotating source code with documentation markup long
antedates Java. Around 1970 Peter Conklin was doing that with MACRO-10
sources and RUNOFF.[1]

This is an old, old idea; it has its origins in the design of COBOL,
which was intended to be readable by non-programmers (specifically by
accountants and legal staff, who could check for regulatory
compliance), and so incorporated various commenting mechanisms,
including "NOTE" paragraphs with arbitrary text embedded in the
source. The idea of extracting documentation from the source, as
opposed to keeping the source as part of the documentation, showed up
about ten years later, toward the end of the 1960s.

> Compare that with the requirement that C
> documentation must be a separately maintained (n|g)roff text file

This "requirement" is a fantasy. The C language does not specify any
documentation mechanism. There are any number of approaches to
combining documentation and source code for C, including javadoc-like
systems such as Doxygen and far more ambitious Literate Programming
systems such as cweb.

> that
> can be almost unreadable in raw form, though the latest versions of less
> do remove a lot of the formatting and checking nausea.

There's no reason why roff sources need to be "unreadable in raw
form", except that they were written by careless authors. And,
incidentally, groff is a relative latecomer; "classical" UNIX offered
nroff and troff executables (typically two links to the same binary),
and later ditroff. groff is just the GNU implementation of the roff
family, with their usual random grab-bag of additional features.

nroff and troff are of course descended from CTSS RUNOFF, via the
PDP-7 roff (written in BCPL), then the first UNIX roff for the PDP-11,
followed by nroff, then troff.


[1]
https://groups.google.com/group/alt.folklore.computers/browse_thread/thread/707c7faadd3b85dd/16871937ef091948

Ney André de Mello Zunino

unread,
Jun 22, 2011, 2:55:13 PM6/22/11
to
On 20/06/2011 16:20, blm...@myrealbox.com wrote:

> Um, has anyone else pointed out that these two programs don't do the
> same thing? Unless the C++ implemented by GCC is broken, the C++
> program reads a whitespace-delimited string, while the Java program
> reads a full line of text.

Agreed. An equivalent C++ program to the proposed Java version which
reads all input until a \newline\ is found would be something like:

***

#include <iostream>
#include <string>

int main() {
std::cout << "Your name? ";
std::string name;
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
}

***

As a side note, the OP's code unnecessarily included /using/
declarations (names were already used in qualified form) and /endl/
(where '\n' should have sufficed). But I digress.

Regards,

--
Ney Andr� de Mello Zunino

blmblm.m...@gmail.com

unread,
Jun 22, 2011, 4:04:21 PM6/22/11
to
In article <its9fk$5jt$1...@dont-email.me>,

Tobias Blass <tobia...@gmx.net> wrote:
> On 2011-06-21, blmblm myrealbox.com <blmblm.m...@gmail.com> wrote:
> > In article <itpi56$9du$1...@dont-email.me>,
> > Tobias Blass <tobia...@gmx.net> wrote:
> >> On 2011-06-20, blmblm myrealbox.com <blmblm.m...@gmail.com> wrote:
> >> > In article <itlgsn$vr8$1...@dont-email.me>,
> >> > Jeff Higgins <je...@invalid.invalid> wrote:
> >> >>
> >> >> On 06/19/2011 02:36 PM, Saeed Amrollahi wrote:
> >> >> > On Jun 19, 6:31 pm, Jeff Higgins<j...@invalid.invalid> wrote:
> >> >> >> On 06/19/2011 09:06 AM, Saeed Amrollahi wrote:
> >> >> >>
> >> >> >>> What are the problems of my code and how can I write
> >> >> >>> a better one. Please throw some light.
> >> >> >>
> >> >> >> What means better?
> >> >> >
> >> >> > For example using less abstractions and less involve with Java
> >> >> > stream class hierarchy.
> >> >>
> >> >> For a beginner, learning to write C in Java is unhelpful.
> >> >
> >> > Even in C one would not be likely to input a string by reading one
> >> > charaacter at a time -- in a beginner program at least.

[ snip ]

> >> Hmm at least in K&R (the inofficial standard C learning book) you often find
> >> while((c=getchar())!=EOF)
> >>
> >> It's less performant than reading whole blocks but in many cases much simpler
> >> (And that's what matters in a learning book)
> >
> > Well, if you say so (my copy of K&R is not easily accessed right
> > now). Certainly that style makes sense in examples in which
> > the goal is to process a character at a time (to classify/count
> > characters, for example, or to copy one file to another).
> >
> > But is this style used in examples in which the objective is to
> > collect one whitespace-delimited "string" and print it? Huh.
> > Maybe I need to reread K&R ....
> >
>
> Obviously it is not the right choice for any problem you might encounter (the
> K&R examples are copy input to output, count characters, count lines etc.) but
> there are situations where getchar() is useful and one should be aware that
> it exists. I don't want to say that one should use it everywhere.

Well, we agree that there are situations in which reading input
a character at a time makes perfect sense, and others in which it
doesn't. I claim that the OP's greeting program is in the second
category. You might disagree!

Message has been deleted

Arne Vajhøj

unread,
Jul 23, 2011, 10:15:47 PM7/23/11
to
On 6/19/2011 3:15 PM, Saeed Amrollahi wrote:
> On Jun 19, 8:36 pm, rossum<rossu...@coldmail.com> wrote:

>> On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
>> <amrollahi.sa...@gmail.com> wrote:
>>> I'm a C++ programmer and I started to learn Java. After famous "Hello
>>> World"
>>> program, the obvious code is "Say hello to specific people". Program
>>> asked
>>> user's name, then print a greeting message.

>> Stream readers are more often used for binary input. For text input
>> people tend to use the java.util.Scanner class.
>>
>> public static void main(String[] args) {


>> System.out.print("Please enter your first name: ");

>> Scanner sc = new Scanner(System.in);
>> String name = sc.nextLine();
>> System.out.println("Hello, " + name);
>> }
>
> What is the Scanner?

Something that scan's - in the same meaning as scanf.

> Why we use nextLine?

Some text plus hitting the return key is called a line,
so nextLine describes pretty well what it does.

> What's the relation of
> such concepts with a simple greeting program.

> Why the code for writing "Hello, world" is in chapter 1, page 1
> of The Java Programming Language, but the code of greeting may be in
> Chapter 20!

It should not be.

Simple use of Scanner should be in one of the first chapters.

If it is not then it can be because the book is old.

Scanner is a late invention.

Before Scanner:

Scanner sc = new Scanner(System.in);
String name = sc.nextLine();

would be done as:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();

But that is not easier.

Also note that the Java API is pretty big.

Java 1.6 has approx. 3000 classes with approx. 100000
methods.

No book can cover everything.

So it is essential that you learn to find things in the
Java API docs.

Arne


paambuu

unread,
Jan 12, 2023, 12:52:08 AM1/12/23
to

paambuu

unread,
Jan 12, 2023, 12:53:30 AM1/12/23
to
Interactive Web-based Guideline for the Efficiency of Household Electric Power Consumption
Properties of ‘Good’ Java Examples
A Java Framework for Broadcast Encryption Algorithms
Speech To Text Conversion using Java API
A framework for Rapid Development of Dynamic Binary Translators
Pagination Using Servlet and JSP
Improved Statistics Handling
Rich Internet Applications for the Enterprise: A comparative study of WebWork and Java Web Start
Simple Search Engine in JAVA Servlets
Performance Analysis of JavaScript
Simple Railway Reservation in JAVA
Simple Chat Program in JAVA
Weather Report Application in JAVA
Online Address Book in JAVA
Java FTP Proxy Server
Mini Orkut Using JAVA
Inventory Management System in JAVA
Net Conference using Java
Telephone Billing System
Vehicle Investigation System in JSP
Simple JAVA Search Engine
Stock Market Trading
Embedded Internet for Pulse Oximeters
Image Processing in Java
Pocket Tanks Game Java Project
Internet Banking Java Project
Hospital Management Java Project
Teachers Feedback Form Java Project
Online Job Portal Java Project
Online Examination Java Project
Alumini Database Java Project
Virtual Classroom Java Project
Lan Chat and File Sharing Java Project
Online Exam Java Project
Java Game mini Project
Online Shopping Java Project
Online Library Management System Java Project
Feedback Collection System java project
Text Editor in Java Project
Moving Balls using Java Applet
Online Reservation System Java Project
Web skeletonizer service
Web Enabled Manufacturing Process Java Project
Album Manager Java Project
Global Communication Network Java Project
Library System Java Project
Link Handler System Java Project
Crypto system Java Project
Scheduling and Dispatching Java Project
Intranet Mailing System Java Project
Online Examination System Java Project
Business to Customer System Java Project
University Admission & Maintenance System Java Project
Campaign Management System Java Project
Content Management System Java Project
Digital Library System Java Project
Contract Labour Management System Java Project
Pay Roll System Project using Java
Revenue Recovery System Java Project
Online medical Booking Store Java Project
Client Management System Java Project
Tele Dormitory System Java Project
Reusable CAPTCHA security engine Java Project
Mobile Service Provider System Java Project
Forestry Management System Java Project
Distributed Channel management System Java Project
Online Tenders Management System Java Project
Job Portal System Java Project
Energy Audit Processing System Java Project
Collector Monthly Review System Java Project
Grievance Handling System Java Project
Student Project Allocation and Management Java Project
Web Based Reporting System Java Project
Vehicle Identification System Java Project
Diamond Shipping System Java Project
Visa Processing System Java Project
Enterprise Fleet Management System Java Project
Global Communication Media Java Project
HR Help Desk System Java Project
SQL Workbench Java Project
Remarketing System Java Project
Cargo Express Courier Java Project
Automated Sports Club Java Project
Multi Banking System Java Project
Java Application World Java Project
Cricket Game Java Java Project
Email Program System Java Project
Employee Information and Payroll System Java Project
Complete Mailing System Java Project
Complete Banking System Java Project
College Library Application System Java Project
Colleges Enrollment System Java Project
Car Sales System Java Project
Bus Booking System Java Project
Bug Tracking System Java Project
Airline Reservation System Java Project
Beat It Game in Java Project
Civilization Game Project Java Project
Airways Reservation System Java Project
Airstrike System Game Java Project
Pong Game Java Project Java Project
Faculty Book System Java Project
Bank Application System Java Project
ATM Database System Java Project
Advanced Payroll System Java Project
Vehicle Identification System Java Project
ISP Automation System Java Project
Life Insurance Management System Java Project
Help Desk Management System Java Project
Datamart Management System Java Project
Automated Sports Club System Java Project
University Search Engine Java Project
Online Exam Suite Java Project
Forensic Management System Java Project
Student Registration System Java Project
E Mail Scanning Project Java Project
Criminal Face Detection System Java Project
Forestry Management System Java Project
Stores Management System Java Project
Employee Time Scheduler System Java Project
Online Wedding Planner Java Project
Crime Record Management System Java Project
Venue Management System Java Project
Employee Management System Java Project
Inventory Management System Java Project
Citizen Card System Java Project
Visa Processing System Java Project
Employee Payroll System Java Project
Multi Vendor Market Place Java Project
Online Grocery Ordering System Java Project
Hotel Booking System Java Project
Online Food Ordering System Java Project
Student Management System Java Project
B.Tech Projects Download Java Project
Campus Recruitment System Java Project
Online Historical Porn
porn site management
porn videos downloader
hentai sites
oombu
0 new messages