tags:

views:

99

answers:

3

Hi,

I'm new to java and having problems with getting input. This is my code which seems to get the first input as required, but then skips the next two "read" function calls?

Any suggestions?

     //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int battMax, battMin, numNodes=0;
    System.out.print("Enter minimum battery level:");
    try {
         battMin = br.read();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.print("Enter maximum battery level:");
     try {
        battMax = br.read();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.print("Enter number of nodes required:");
     try {
        numNodes = br.read();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
+3  A: 

br.read() reads a char. Use Integer.parseInt(br.readLine()) which will read a whole line and convert it into an int.

Also, initialize all your local variables:

int battMax=0, battMin=0, numNodes=0;
Chandra Patni
I would suggest *not* initializing local variables to dummy values. Instead, declare them as late as possible and explicitly use a default if an exception occurs.
Jon Skeet
+6  A: 

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.

Jon Skeet
A: 

If you're using java 1.5 or later, you can use the java.util.Scanner

public static getInt(String prompt){
    int n = 0;
    try {
        System.out.print(prompt);
        Scanner kb = new Scanner(System.in);
        n = kb.nextInt();
    }
    catch(Exception ex){
       ex.printStackTrace();
    }
    return n;
}

Sample Usage:

int battMax = getInt("Enter minimum battery level:");
int battMin = getInt("Enter maximum battery level:");
int numNodes = getInt("Enter number of nodes required:");
jerjer
I think it may be worth pointing out that that isn't really a production-ready way of handling exceptions...
Jon Skeet