tags:

views:

259

answers:

4

What class can I use for reading an integer variable in Java?

+2  A: 

Check this one:

public static void main(String[] args) {
    String input = null;
    int number = 0;
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        input = bufferedReader.readLine();
        number = Integer.parseInt(input);
    } catch (NumberFormatException ex) {
       System.out.println("Not a number !");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
thelost
What's the point in catching the `NumberFormatException` and then printing the stack trace?
missingfaktor
Yeah, quite senseless! :-) I just changed it, thanks!
thelost
+5  A: 

You can use java.util.Scanner (API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

polygenelubricants
I second that solution.
Bozhidar Batsov
+3  A: 

If you are using Java 6, you can use the following oneliner to read an integer from console:

int n = Integer.parseInt(System.console().readLine());
missingfaktor
A: 

Take a look at Teletype.java from the Java Project Template. I believe it is exactly the utility you want.

Michael Aaron Safyan