Re: The greeting code in Java
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