br.read()
is going to read a single character. Furthermore, if you're reading from System.in
it's likely to only see something when the user presses return - at which point, if you're on Windows, it will have an extra \r
and \n
to read (or just \n
on Unix).
I suspect you'll find the values read by your second and third read()
calls are \r
and \n
.
Furthermore, you're not actually getting the values you want to anyway - if someone enters '1' then you'll get a value of 49, as that's the Unicode value for that character.
You should use readLine()
to read a line at a time (and then parse the string with Integer.parseInt()
. Alternatively, you could use the Scanner
class - I can't say I've ever used it myself, but it may be useful to you.
Finally, there's a lot of repetition in that code - I would suggest you refactor it by creating a utility method. For example, you might have:
public static int promptUserForInt(String prompt, int defaultValue,
BufferedReader reader)
throws IOException
{
while (true)
{
System.out.print(prompt);
try
{
String line = reader.readLine();
return Integer.parseInt(line);
}
catch (NumberFormatException e)
{
// Adjust as appropriate...
System.out.println
("Unable to parse input; please enter an integer.");
}
}
}
You can then use this very easily:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int battMax = promptUserForInt("Enter minimum battery level:");
int battMin = promptUserForInt("Enter maximum battery level:");
int numNodes = promptUserForInt("Enter number of nodes required:");
You could refactor further by taking in a Writer
or BufferedWriter
to display the prompt in - that way you could test it more easily.
Finally, I would suggest that you don't wrap each bit in a catch block for IOException
; if you can't read the console input, I suspect you don't want to continue anyway, so you want to behave the same way whether the first input generates this exception or the second or third. Either declare that your method throws IOException
, or have all three lines in the same try
block, handled by the same catch
block.