How to read integer value from the standard input in Java

Nehil Verma picture Nehil Verma · Mar 24, 2010 · Viewed 552.8k times · Source

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

Answer

polygenelubricants picture polygenelubricants · Mar 24, 2010

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?).