Read integers from console in Java


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
", 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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements