Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #5372 > unrolled thread

The greeting code in Java

Started bySaeed Amrollahi <amrollahi.saeed@gmail.com>
First post2011-06-19 06:05 -0700
Last post2011-06-22 15:55 -0300
Articles 17 — 11 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  The greeting code in Java Saeed Amrollahi <amrollahi.saeed@gmail.com> - 2011-06-19 06:05 -0700
    Re: The greeting code in Java rossum <rossum48@coldmail.com> - 2011-06-19 17:36 +0100
      Re: The greeting code in Java Saeed Amrollahi <amrollahi.saeed@gmail.com> - 2011-06-19 12:15 -0700
        Re: The greeting code in Java Martin Gregorie <martin@address-in-sig.invalid> - 2011-06-19 19:46 +0000
          Re: The greeting code in Java Saeed Amrollahi <amrollahi.saeed@gmail.com> - 2011-06-19 22:34 -0700
            Re: The greeting code in Java Jukka Lahtinen <jtfjdehf@hotmail.com.invalid> - 2011-06-23 11:43 +0300
          Re: The greeting code in Java Martin Gregorie <martin@address-in-sig.invalid> - 2011-06-20 10:13 +0000
            Re: The greeting code in Java Michael Wojcik <mwojcik@newsguy.com> - 2011-06-22 09:29 -0400
        Re: The greeting code in Java Joshua Cranmer <Pidgeot18@verizon.invalid> - 2011-06-19 16:00 -0400
        Re: The greeting code in Java Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-06-19 16:05 -0400
          Re: The greeting code in Java Saeed Amrollahi <amrollahi.saeed@gmail.com> - 2011-06-19 22:40 -0700
        Re: The greeting code in Java rossum <rossum48@coldmail.com> - 2011-06-19 22:28 +0100
        Re: The greeting code in Java Arne Vajhøj <arne@vajhoej.dk> - 2011-07-23 22:15 -0400
    Re: The greeting code in Java Roedy Green <see_website@mindprod.com.invalid> - 2011-06-19 21:14 -0700
    Re: The greeting code in Java Roedy Green <see_website@mindprod.com.invalid> - 2011-06-19 21:23 -0700
    Re: The greeting code in Java blmblm@myrealbox.com <blmblm.myrealbox@gmail.com> - 2011-06-20 19:20 +0000
      Re: The greeting code in Java Ney André de Mello Zunino <zunino@softplan.com.br> - 2011-06-22 15:55 -0300

#5372 — The greeting code in Java

FromSaeed Amrollahi <amrollahi.saeed@gmail.com>
Date2011-06-19 06:05 -0700
SubjectThe greeting code in Java
Message-ID<f61fee62-589e-4ad1-a9ef-a54e2b589e5b@s9g2000yqm.googlegroups.com>
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

[toc] | [next] | [standalone]


#5387

Fromrossum <rossum48@coldmail.com>
Date2011-06-19 17:36 +0100
Message-ID<ld8sv6tugbkdq7n1dc0d4ja0o604rr6n5q@4ax.com>
In reply to#5372
On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
<amrollahi.saeed@gmail.com> 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

[toc] | [prev] | [next] | [standalone]


#5399

FromSaeed Amrollahi <amrollahi.saeed@gmail.com>
Date2011-06-19 12:15 -0700
Message-ID<b70ab7d1-fe03-413e-ba87-6819ae24973e@hd10g2000vbb.googlegroups.com>
In reply to#5387
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:
> >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

[toc] | [prev] | [next] | [standalone]


#5401

FromMartin Gregorie <martin@address-in-sig.invalid>
Date2011-06-19 19:46 +0000
Message-ID<itljmt$rib$1@localhost.localdomain>
In reply to#5399
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       |

[toc] | [prev] | [next] | [standalone]


#5417

FromSaeed Amrollahi <amrollahi.saeed@gmail.com>
Date2011-06-19 22:34 -0700
Message-ID<cf260d84-d636-419b-a128-6009d2a2c1da@k6g2000yqc.googlegroups.com>
In reply to#5401
On Jun 19, 10:46 pm, Martin Gregorie <mar...@address-in-sig.invalid>
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

[toc] | [prev] | [next] | [standalone]


#5570

FromJukka Lahtinen <jtfjdehf@hotmail.com.invalid>
Date2011-06-23 11:43 +0300
Message-ID<m362nxgcp9.fsf@despammed.com>
In reply to#5417
Saeed Amrollahi <amrollahi.saeed@gmail.com> writes:
> On Jun 19, 10:46 pm, Martin Gregorie <mar...@address-in-sig.invalid>

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

[toc] | [prev] | [next] | [standalone]


#5421

FromMartin Gregorie <martin@address-in-sig.invalid>
Date2011-06-20 10:13 +0000
Message-ID<itn6fg$894$1@localhost.localdomain>
In reply to#5401
On Sun, 19 Jun 2011 20:24:13 +0000, Stefan Ram wrote:

> Martin Gregorie <martin@address-in-sig.invalid> 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       |

[toc] | [prev] | [next] | [standalone]


#5523

FromMichael Wojcik <mwojcik@newsguy.com>
Date2011-06-22 09:29 -0400
Message-ID<itsr3d01ad3@news1.newsguy.com>
In reply to#5421
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.folklore.computers/browse_thread/thread/707c7faadd3b85dd/16871937ef091948

[toc] | [prev] | [next] | [standalone]


#5402

FromJoshua Cranmer <Pidgeot18@verizon.invalid>
Date2011-06-19 16:00 -0400
Message-ID<itlkgl$p80$1@dont-email.me>
In reply to#5399
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::operator<< 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

[toc] | [prev] | [next] | [standalone]


#5403

FromEric Sosman <esosman@ieee-dot-org.invalid>
Date2011-06-19 16:05 -0400
Message-ID<itlkrg$tb2$1@dont-email.me>
In reply to#5399
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
esosman@ieee-dot-org.invalid

[toc] | [prev] | [next] | [standalone]


#5420

FromSaeed Amrollahi <amrollahi.saeed@gmail.com>
Date2011-06-19 22:40 -0700
Message-ID<f0073f0c-9fd5-4032-b71b-4051455ca853@y30g2000yqb.googlegroups.com>
In reply to#5403
On Jun 19, 11:05 pm, Eric Sosman <esos...@ieee-dot-org.invalid> 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
> esos...@ieee-dot-org.invalid

[toc] | [prev] | [next] | [standalone]


#5410

Fromrossum <rossum48@coldmail.com>
Date2011-06-19 22:28 +0100
Message-ID<9qpsv6posju2o7bfv777hg2clgbphj3rl2@4ax.com>
In reply to#5399
On Sun, 19 Jun 2011 12:15:01 -0700 (PDT), Saeed Amrollahi
<amrollahi.saeed@gmail.com> wrote:

>What is the Scanner? 
As Martin said, you need to read the Javadoc:
(http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html)

Java is a relatively small language with a huge standard library.  You
cannot understand the language without knowing the basics of the
library.  The library is described in the Javadocs.  If you have not
done so already, download them from
(http://www.oracle.com/technetwork/java/javase/downloads/index.html#docs)
and install them on your computer.  Your IDE should be able to link to
them and use them to help you.

>Why we use nextLine?
It returns the next line of input as a String.  Since your program
reads a line of input it is the obvious method to use.

>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!
Ask the authour of the book you are using.

rossum

>  -- Saeed

[toc] | [prev] | [next] | [standalone]


#6493

FromArne Vajhøj <arne@vajhoej.dk>
Date2011-07-23 22:15 -0400
Message-ID<4e2b8058$0$316$14726298@news.sunsite.dk>
In reply to#5399
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





[toc] | [prev] | [next] | [standalone]


#5413

FromRoedy Green <see_website@mindprod.com.invalid>
Date2011-06-19 21:14 -0700
Message-ID<v6itv652s7dt1sjm5djvncvcmgc607ff33@4ax.com>
In reply to#5372
On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
<amrollahi.saeed@gmail.com> 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.

[toc] | [prev] | [next] | [standalone]


#5414

FromRoedy Green <see_website@mindprod.com.invalid>
Date2011-06-19 21:23 -0700
Message-ID<nditv65to0jlljmnfpf9hovqphedn2te5s@4ax.com>
In reply to#5372
On Sun, 19 Jun 2011 06:05:53 -0700 (PDT), Saeed Amrollahi
<amrollahi.saeed@gmail.com> 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.

[toc] | [prev] | [next] | [standalone]


#5429

Fromblmblm@myrealbox.com <blmblm.myrealbox@gmail.com>
Date2011-06-20 19:20 +0000
Message-ID<969kscFjduU6@mid.individual.net>
In reply to#5372
In article <f61fee62-589e-4ad1-a9ef-a54e2b589e5b@s9g2000yqm.googlegroups.com>,
Saeed Amrollahi  <amrollahi.saeed@gmail.com> 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.

[toc] | [prev] | [next] | [standalone]


#5535

FromNey André de Mello Zunino <zunino@softplan.com.br>
Date2011-06-22 15:55 -0300
Message-ID<ittdqf$v3n$1@speranza.aioe.org>
In reply to#5429
On 20/06/2011 16:20, blmblm@myrealbox.com 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

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web