It's not a secret anymore!*
The moose likes I/O and Streams and the fly likes method to read a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "method to read a string" Watch "method to read a string" New topic
Author

method to read a string

CH Low
Greenhorn

Joined: Aug 25, 2001
Posts: 1
I tried writing a String input method and had a problem
with throwing IOException so i tried to use a try/catch statement, but then
the variable to be returned is said to be "not initialised" by the
compiler. wats the problem? can anyone help? here's the code;
public static String getString()
{
InputStreamReader input;
BufferedReader bR;
String s;
try{
input = new InputStreamReader(System.in);
bR = new BufferedReader(input);
s = bR.readLine();
}
catch (IOException e)
{
System.out.println("error");
System.exit(0);
}
return s; // there seems to be a problem with returning s!
}
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
In a method, every variable must be assigned a value before being used. There are no default values, as there are for instance and class level fields. If BufferedReader.readLine() threw an IOException, s would never have been assigned a value. Now, we both know that the chances of that happening are slim to none, but the compiler only knows the Java Language Specification. Before you return 's', you must initialize it. To do that, replace 'String s;' with 'String s = null;'
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: method to read a string