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
2010-03-24 07:54:12
What's the point in catching the `NumberFormatException` and then printing the stack trace?
missingfaktor
2010-03-24 08:13:48
Yeah, quite senseless! :-) I just changed it, thanks!
thelost
2010-03-24 08:16:47
+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
2010-03-24 07:56:10
+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
2010-03-24 08:06:50
A:
Take a look at Teletype.java from the Java Project Template. I believe it is exactly the utility you want.
Michael Aaron Safyan
2010-03-24 08:40:35