How to read integer value from the standard input in Java

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


Solution 1:

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

Solution 2:

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());

Solution 3:

Here I am providing 2 examples to read integer value from the standard input

Example 1

import java.util.Scanner;
public class Maxof2
{ 
  public static void main(String args[])
  {
       //taking value as command line argument.
        Scanner in = new Scanner(System.in); 
       System.out.printf("Enter i Value:  ");
       int i = in.nextInt();
       System.out.printf("Enter j Value:  ");
       int j = in.nextInt();
       if(i > j)
           System.out.println(i+"i is greater than "+j);
       else
           System.out.println(j+" is greater than "+i);
   }
 }

Example 2

public class ReadandWritewhateveryoutype
{ 
  public static void main(String args[]) throws java.lang.Exception
  {
System.out.printf("This Program is used to Read and Write what ever you type \nType  quit  to Exit at any Moment\n\n");
    java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
     String hi;
     while (!(hi=r.readLine()).startsWith("quit"))System.out.printf("\nYou have typed: %s \n",hi);
     }
 }

I prefer the First Example, it's easy and quite understandable.
You can compile and run the JAVA programs online at this website: http://ideone.com