The greeting code in Java

Discussion in 'Java' started by Saeed Amrollahi, Jun 19, 2011.

  1. 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, Jun 19, 2011
    #1
    1. Advertising

  2. Saeed Amrollahi

    Aéris Guest

    -----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-----
    Aéris, Jun 19, 2011
    #2
    1. Advertising

  3. On Jun 19, 4:19 pm, Aéris <> 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
    Saeed Amrollahi, Jun 19, 2011
    #3
  4. Saeed Amrollahi

    Jeff Higgins Guest

    On 06/19/2011 09:44 AM, Saeed Amrollahi wrote:
    > On Jun 19, 4:19 pm, Aéris<> wrote:
    >
    > From point of educational view, do you think my code or your code
    > is as simple as the C++ version?
    >

    What means simple?
    Jeff Higgins, Jun 19, 2011
    #4
  5. On Jun 19, 5:13 pm, Jeff Higgins <> wrote:
    > On 06/19/2011 09:44 AM, Saeed Amrollahi wrote:> On Jun 19, 4:19 pm, A ris<>  wrote:
    >
    > >  From point of educational view, do you think my code or your code
    > > is as simple as the C++ version?

    >
    > 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
    Saeed Amrollahi, Jun 19, 2011
    #5
  6. Saeed Amrollahi

    Jeff Higgins Guest

    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?
    Jeff Higgins, Jun 19, 2011
    #6
  7. Saeed Amrollahi

    Aéris Guest

    -----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-----
    Aéris, Jun 19, 2011
    #7
  8. Saeed Amrollahi

    Jeff Higgins Guest

    On 06/19/2011 10:17 AM, Saeed Amrollahi wrote:
    > On Jun 19, 5:13 pm, Jeff Higgins<> wrote:
    >> On 06/19/2011 09:44 AM, Saeed Amrollahi wrote:> On Jun 19, 4:19 pm, A ris<> wrote:
    >>
    >>> From point of educational view, do you think my code or your code
    >>> is as simple as the C++ version?

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

    What language does the beginner wish to learn?
    Jeff Higgins, Jun 19, 2011
    #8
  9. 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
    Stanimir Stamenkov, Jun 19, 2011
    #9
  10. Saeed Amrollahi

    Aéris Guest

    -----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-----
    Aéris, Jun 19, 2011
    #10
  11. Saeed Amrollahi

    Stefan Ram Guest

    Jeff Higgins <> writes:
    >What means simple?


    10 INPUT "Please enter your first name: "; N$
    20 PRINT "Hello, "; N$; "!"
    30 END
    Stefan Ram, Jun 19, 2011
    #11
  12. Saeed Amrollahi

    Jeff Higgins Guest

    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, Jun 19, 2011
    #12
  13. Saeed Amrollahi

    Jeff Higgins Guest

    On 06/19/2011 11:24 AM, Aéris wrote:
    >
    > Shame on me…
    > My finger slipped on Eclipse…
    >

    Pretty, slick, Eclipse. :)
    Jeff Higgins, Jun 19, 2011
    #13
  14. 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
    Stanimir Stamenkov, Jun 19, 2011
    #14
  15. Saeed Amrollahi

    Jeff Higgins Guest

    On 06/19/2011 11:36 AM, Stefan Ram wrote:
    > Jeff Higgins<> 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.
    Jeff Higgins, Jun 19, 2011
    #15
  16. Saeed Amrollahi

    Stefan Ram Guest

    Saeed Amrollahi <> writes:
    >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() +
    "!" ); }}
    Stefan Ram, Jun 19, 2011
    #16
  17. Saeed Amrollahi

    Jeff Higgins Guest

    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, Jun 19, 2011
    #17
  18. Saeed Amrollahi

    Jeff Higgins Guest

    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, Jun 19, 2011
    #18
  19. Saeed Amrollahi

    Jeff Higgins Guest

    On 06/19/2011 01:11 PM, Jeff Higgins wrote:
    > 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>
    >
    >

    public class Main {
    public static void main(String[] args) {
    System.console().printf("Hello, %1$s!\n",
    System.console().readLine("Please enter your first name: "));
    }
    }
    Jeff Higgins, Jun 19, 2011
    #19
  20. On Jun 19, 6:31 pm, Jeff Higgins <> 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.
    -- Saeed
    Saeed Amrollahi, Jun 19, 2011
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Leon

    Url / Page Greeting?

    Leon, Dec 3, 2004, in forum: ASP .Net
    Replies:
    2
    Views:
    360
  2. Matthias S.
    Replies:
    1
    Views:
    416
    OHM \( Terry Burns \)
    Mar 27, 2005
  3. Sharon
    Replies:
    6
    Views:
    439
    Sharon
    Jan 3, 2004
  4. tak
    Replies:
    0
    Views:
    501
  5. Saeed Amrollahi

    The greeting code in Java

    Saeed Amrollahi, Jun 19, 2011, in forum: Java
    Replies:
    15
    Views:
    858
    Arne Vajhøj
    Jul 24, 2011
Loading...

Share This Page