Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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\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
Advertisements