wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android 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;'
 
wood burning stoves
 
subject: method to read a string
 
Similar Threads
tic tac toe and switch statement
making Thread of methods
Help with sockets
read lines from Writer write method
I/O in Java