Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

method to read a string

 
CH Low
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;'
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic