Read integers from console in Java

Java 8Object Oriented ProgrammingProgramming

To read integers from console, use Scanner class.

Scanner myInput = new Scanner( System.in );

Allow a use to add an integer using the nextInt() method.

System.out.print( "Enter first integer: " );
int a = myInput.nextInt();

In the same way, take another input in a new variable.

System.out.print( "Enter second integer: " );
Int b = myInput.nextInt();

Let us see the complete example.

Example

import java.util.Scanner;
public class Demo {
   public static void main( String args[] ) {
      Scanner myInput = new Scanner( System.in );
      int a;
      int b;
      int sum;
      System.out.print( "Enter first integer: " );
      a = myInput.nextInt();
      System.out.print( "Enter second integer: " );
      b = myInput.nextInt();
      sum = a + b;
      System.out.printf( "Sum = %d\n", sum );
   }
}

We added the following two integer values from the console.

5
10

After adding the values and running the program, the following output can be seen.

Enter first integer: 5
Enter second integer: 10
Sum = 15
raja
Published on 13-Nov-2018 10:03:26
Advertisements