The greeting code in Java

S

Saeed Amrollahi

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
 
A

Aéris

-----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-----
 
S

Saeed Amrollahi

-----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
 
S

Saeed Amrollahi

What means simple?

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
 
A

Aéris

-----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-----
 
J

Jeff Higgins

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.
What language does the beginner wish to learn?
 
S

Stanimir Stamenkov

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: ");
}
 
A

Aéris

-----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-----
 
J

Jeff Higgins

Le 19/06/2011 17:06, Stanimir Stamenkov a écrit :

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();
}
 
S

Stanimir Stamenkov

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.
 
J

Jeff Higgins

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.
 
S

Stefan Ram

Saeed Amrollahi said:
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;

public class Main
{
public static void main( final java.lang.String[] args )
{
java.lang.System.out.print( "Please enter your first name: " );
java.lang.System.out.flush();
java.lang.System.out.println
( "Hello, " +
new java.util.Scanner( java.lang.System.in ).nextLine() +
"!" ); }}
 
J

Jeff Higgins

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top