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

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
 
M

Martin Gregorie

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

Joshua Cranmer

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

Eric Sosman

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

Stefan Ram

Martin Gregorie said:
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.
 
R

Roedy Green

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

Roedy Green

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

Saeed Amrollahi

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.

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

Saeed Amrollahi

[...]
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
 
M

Martin Gregorie

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

blmblm

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

Michael Wojcik

Martin said:
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
 
N

Ney André de Mello Zunino

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

Arne Vajhøj

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
 

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

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top