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
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-----
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
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
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-----
> 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
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-----
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();
}
> 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
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
For example using less abstractions and less involve with Java
stream class hierarchy.
-- Saeed
For a beginner, learning to write C in Java is unhelpful.
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
Actually, I am going to prepare a seminar under the title: C++ vs.
Java
I try to compare C++ and Java from point of programming view.
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 |
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
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
eso...@ieee-dot-org.invalid
Le 19/06/2011 21:06, Saeed Amrollahi a �crit :
> I try to compare C++ and Java from point of programming view.
In this case, do not just compare language each others, but also related
tools.
Maven or Graddle are must have in the Java World, or other tools like
Jenkins, Sonar?
Java is not just a language, it's a World. It most important part is
also community and tools.
- --
Aeris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
iQEcBAEBAgAGBQJN/lbIAAoJEK8zQvxDY4P9kyAH/002cDmNtahTv9VsSw0V7W3T
OzUTF9QGHZuuhjiO0dpfStgt0CsQsr+LdueRL1yqDxSBFlMjunvAoF3/2J1fQ10j
LdZkpQ1zYP9X5DXmuzMFmYILhtwCX2Q9HS2Mt+igs2zVrhDyQvSP2wArfxKxTsSD
XTrQ1j+pgMuOuVejxHOr6/oWeLjhCDKV4taMcm+F9uwp5Ze7q2T5ZnOi6tF5sMvB
9WYemCtfni2TPDtmklqwyPMBsMmzUJT10G23unlmXGxmh33XMglxEkgNltQk11AF
acceSLsNI9YMeTvvEkejCxae1Ok57nruEPl2jkWrAagjc5/OxEW3rLjXLxc+m18=
=sq/+
-----END PGP SIGNATURE-----
If that is what you're explaining in Java, you also need to explain for
C++ stack constructed-objects, references, #include (trust me, beginners
can get very confused about #include, as simple as it looks), and
probably the entire iostream interfaces if you're talking about Java's
stream class hierarchy.
> I believe the C++ code is simpler for a beginner.
If it's simpler, it's only superficially so. C++'s interfaces heavily
optimize for the most common case and render the development of the more
critical components inordinately more difficult. For example, a fair
amount of my work has to worry about the use of international characters
and multiple charsets (it's not unimaginable that I have to use one
stream to write in two simultaneous charsets (i.e., the control protocol
is in UTF-8 but I send 8-bit MIME payloads of ISO 8859-1)). In Java, I
can keep both the raw Stream and a controlling Reader/Writer around and
use the character-based one for control information and the octet-based
one for data payloads.
And, naturally, any talk of C++ being simpler becomes hard to stomach
once you introduce templates, i.e., any use of the STL. std::string
isn't actually a class, it's actually std::basic_string<char,
std::char_traits<char>, std::allocator<char> >, as every error message
involving std::set<std::string> will helpfully inform you. I mean
std::set<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::less<std::basic_string<char,
std::char_traits<char>, std::allocator<char> > >,
std::allocator<std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >. Have fun debugging your template errors!
In all fairness, the first 200 pages or so of the C standard are
language semantics, which C++ redefines for itself anyways. It's the
library and a few of the annexes that are important for C++ (so about
300 pages, give or take). Of course, you might want to add for some more
information specs like IEEE 754 (~70 pages) if you want to know more
information about floating points.
The JLS itself is 684 pages, compared to the ~450 pages that C++ takes
to explain its language. The C++0x library takes around 800 pages to
explain the rough equivalent to large hunks of java.lang and java.util.
On the other hand, the JLS is a lot more explicit and burns through
space with examples, so it is relatively low in information density for
a specification. The standard Java API is also probably the best example
of API documentation in widespread usage.
>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
Ok, I will join the fun:
Mathematica:
------------------
name = InputString["Name?"]
Print["Hello "<>name];
-----------------
Matlab:
-------------------------------
name = input('Name?','s')
fprintf('hello %s\n',name)
--------------------------
--Nasser
>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.
>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.
Well, I guess the above is a good example of why you Java
programmers get the big bucks !
--Nasser
In the hq9ni language, it's even easier:
i
I'll download it and use it.
-- Saeed Amrollahi
> Martin Gregorie <mar...@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.
Most people don't write "Hello" programs, so comparing languages by
counting lines of source code for "Hello" - doesn't really tell you much.
perl -e 'print "Hello $ARGV[0]\n"' Fred
Hello Fred
ksh -c 'print Hello $0' Fred
Hello Fred
I hope you would not think it relevant to conclude that Goldman Sachs,
Microsoft and Notch writing share-trading systems, word processors and
video-games will find it easier to learn Korn shell and not Java, C or C++?
--
RGB
You seem sincere but I can't help wonder:
Who is the intended audience? What is the goal?
Hopefully it's not a usenet seminar posted to both
C++ and Java groups. That's been done, and is a messy format.
> You seem sincere but I can't help wonder:
> Who is the intended audience? What is the goal?
I can almost see a serial type format:
Java: Accounts of My Explorations.
1. Hello
2. Crossing Streams
3. Buildings
...
> Java: Accounts of My Explorations.
> 1. Hello
... The maddening rattle-clank of the trucks on rails subsided as our
train approached Java Station. Outside the dusty, smokey panes of the
stifling car, amid the lush forest of Java, suddenly loomed a great line
of platforms. On and on they seemed to stretch, each different and I
hadn't been informed where to disembark. I reached for my preprocessor;
but the brown-eyed girl, sensing my anxiety, smiled and touched my hand.
"They are all the same" she whispered, "write once, run anywhere, we say
here". Pulling the signalling cord, she said "Come along, we'll get off
here and I'll show you." "We shall say hello and they will all
understand us, and smile and welcome us."
...
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.
[ snip ]
> 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.
Huh. There's actually an explicit "flush" in the implementation?
Interesting. How did you find this out? I'm not a C++ expert but
had not come across a mention of this detail.
Of course, if writing prompts to stdout with the implicit assumption
that the program is being run interactively, flushing the buffer is
what one wants.
Just sayin'.
Even in C one would not be likely to input a string by reading one
charaacter at a time -- in a beginner program at least.
[ snip ]
> Actually, I am going to prepare a seminar under the title: C++ vs.
> Java
> I try to compare C++ and Java from point of programming view.
All the more reason to try for examples that make idiomatic use
of language features, then. Your C++ program doesn't read its input
a character at a time; why should the Java program?
Hmm at least in K&R (the inofficial standard C learning book) you often find
while((c=getchar())!=EOF)
It's less performant than reading whole blocks but in many cases much simpler
(And that's what matters in a learning book)
I know these quotes (every programmer should).
I didn't want to warn of using getchar. I must admit the performance thing was a
guess (and I think I read it somewhere), but even if it is the second part of
the sentence applies. Premature Optimization is mainly evil _because_ you
sacrifice simplicity (there are other reasons but this is the most important
one).
[snip]
>I know these quotes (every programmer should).
>I didn't want to warn of using getchar. I must admit the performance thing was a
>guess (and I think I read it somewhere), but even if it is the second part of
>the sentence applies. Premature Optimization is mainly evil _because_ you
>sacrifice simplicity (there are other reasons but this is the most important
>one).
This point was covered neatly in "Code Complete". At least, it
was in the first edition. I have not read the latest.
McConnell was writing encryption software to run on an original
IBM pc. He optimised and optimised to speed up his C code. Finally,
he hucked it and rewrote in Assembler. His observation was that as
more and more optimisations were added, the code became much less
readable.
I like to optimise for code readability. If code is useful, it
generally will have a long lifetime. That gives more opportunity for
changes being required. Changes are a real bother when the code is
not easily readable.
Sincerely,
Gene Wirchenko
s/charaacter/character/, of course (why do these details only become
apparently *after* posting?)
> Hmm at least in K&R (the inofficial standard C learning book) you often find
> while((c=getchar())!=EOF)
>
> It's less performant than reading whole blocks but in many cases much simpler
> (And that's what matters in a learning book)
Well, if you say so (my copy of K&R is not easily accessed right
now). Certainly that style makes sense in examples in which
the goal is to process a character at a time (to classify/count
characters, for example, or to copy one file to another).
But is this style used in examples in which the objective is to
collect one whitespace-delimited "string" and print it? Huh.
Maybe I need to reread K&R ....
Obviously it is not the right choice for any problem you might encounter (the
K&R examples are copy input to output, count characters, count lines etc.) but
there are situations where getchar() is useful and one should be aware that
it exists. I don't want to say that one should use it everywhere.
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.
> 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
[ snip ]
> >> Hmm at least in K&R (the inofficial standard C learning book) you often find
> >> while((c=getchar())!=EOF)
> >>
> >> It's less performant than reading whole blocks but in many cases much simpler
> >> (And that's what matters in a learning book)
> >
> > Well, if you say so (my copy of K&R is not easily accessed right
> > now). Certainly that style makes sense in examples in which
> > the goal is to process a character at a time (to classify/count
> > characters, for example, or to copy one file to another).
> >
> > But is this style used in examples in which the objective is to
> > collect one whitespace-delimited "string" and print it? Huh.
> > Maybe I need to reread K&R ....
> >
>
> Obviously it is not the right choice for any problem you might encounter (the
> K&R examples are copy input to output, count characters, count lines etc.) but
> there are situations where getchar() is useful and one should be aware that
> it exists. I don't want to say that one should use it everywhere.
Well, we agree that there are situations in which reading input
a character at a time makes perfect sense, and others in which it
doesn't. I claim that the OP's greeting program is in the second
category. You might disagree!
>> 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