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. On Jun 19, 8:36 pm, rossum <> wrote:
    > On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
    >
    >
    >
    > <> 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);
    > >    }
    > >}

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

    >
    > >TIA,
    > >  -- Saeed Amrollahi

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


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

  3. 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 |
     
    Martin Gregorie, Jun 19, 2011
    #3
  4. 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::eek:perator<< 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
     
    Joshua Cranmer, Jun 19, 2011
    #4
  5. Saeed Amrollahi

    Eric Sosman Guest

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

    Stefan Ram Guest

    Martin Gregorie <> 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«.

    However, it has not been man portable together with C,
    while JavaDoc is part of the Java SE. This portability
    and standardization of JavaDoc is its greatest advantage.
     
    Stefan Ram, Jun 19, 2011
    #6
  7. Saeed Amrollahi

    Roedy Green Guest

    On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
    <> 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, Jun 20, 2011
    #7
  8. Saeed Amrollahi

    Roedy Green Guest

    On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
    <> 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.

    --
    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, Jun 20, 2011
    #8
  9. On Jun 19, 10:46 pm, Martin Gregorie <>
    wrote:
    > 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       |


    I'll download it and use it.
    -- Saeed Amrollahi
     
    Saeed Amrollahi, Jun 20, 2011
    #9
  10. On Jun 19, 11:05 pm, Eric Sosman <> wrote:
    > 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.
    >

    Of course I don't do that. Each programming language has its own
    terminology,
    culture, ideals, idioms and styles.
    -- Saeed Amrollahi
    > --
    > Eric Sosman
    >
     
    Saeed Amrollahi, Jun 20, 2011
    #10
  11. On Sun, 19 Jun 2011 20:24:13 +0000, Stefan Ram wrote:

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


    --
    martin@ | Martin Gregorie
    gregorie. | Essex, UK
    org |
     
    Martin Gregorie, Jun 20, 2011
    #11
  12. Saeed Amrollahi

    Guest

    In article <>,
    Saeed Amrollahi <> 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.
     
    , Jun 20, 2011
    #12
  13. 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...read/thread/707c7faadd3b85dd/16871937ef091948
     
    Michael Wojcik, Jun 22, 2011
    #13
  14. On 20/06/2011 16:20, 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
     
    Ney André de Mello Zunino, Jun 22, 2011
    #14
  15. Saeed Amrollahi <> writes:
    > On Jun 19, 10:46 pm, Martin Gregorie <>


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


    > I'll download it and use it.


    If you have a decent web access, it is not necessary to download it if
    you don't want to. You can browse the API javadocs online through
    http://download.oracle.com/javase/6/docs/api/

    and some more documentation can be seen at
    http://download.oracle.com/javase/6/docs/

    --
    Jukka Lahtinen
     
    Jukka Lahtinen, Jun 23, 2011
    #15
  16. Saeed Amrollahi

    Arne Vajhøj Guest

    On 6/19/2011 3:15 PM, Saeed Amrollahi wrote:
    > On Jun 19, 8:36 pm, rossum<> wrote:
    >> On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
    >> <> 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
     
    Arne Vajhøj, Jul 24, 2011
    #16
    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:
    391
  2. Matthias S.
    Replies:
    1
    Views:
    454
    OHM \( Terry Burns \)
    Mar 27, 2005
  3. Sharon
    Replies:
    6
    Views:
    465
    Sharon
    Jan 3, 2004
  4. tak
    Replies:
    0
    Views:
    535
  5. Saeed Amrollahi

    The greeting code in Java

    Saeed Amrollahi, Jun 19, 2011, in forum: Java
    Replies:
    48
    Views:
    2,227
Loading...

Share This Page