We will now make a small program that will input two integers in Java and display their sum. In this program, we will use the methods available in Scanner class to read data typed at keyboard and place it into variables that we specify.
//Input Two Numbers and Display their Sum // imports Scanner class in java.util package import java.util.Scanner; class JavaInputProgram { public static void main (String[] args) { Scanner inputdata=new Scanner(System.in); int num1,num2,result; System.out.print("Enter the First Number : "); num1 = inputdata.nextInt(); System.out.print("Enter the Second Number : "); num2 =inputdata.nextInt(); result=num1 + num2; System.out.println("Sum of "+num1+" and " +num2+" is : "+result); } }
The program on execution will ask you to input two numbers and then display their sum. Before you can use Scanner class in the program, you must import it from the java.util package. This is made possible by using the import declaration as follows,
import java.util.Scanner;
The statement,
Scanner inputData = new Scanner(System.in);
creates a Scanner object named inputData that reads data typed by the user at the keyboard. To create a Scanner object, the new keyword is used. It is followed by a call to the Scanner class constructor which takes an InputStream object (i.e. System. in) as a parameter. The System.in specifies the standard console keyboard input.
The statement,
num1 = inputData.nextInt();
uses the nextInt()method of the Scanner object inputData to obtain an integer typed at the keyboard by the user. When the nextInt() method is executed, the program waits for the user to enter an integer number After the user enters an integer number at the keyboard and presses the enter key, the value is assigned to the variable num1 and the program continues. Similarly, the second number will be entered using the statement,
num2 = inputData.nextInt();
The two numbers that are stored in num1 and num2 variables are added and their result is stored in result variable.
Finally the statement,
System.out.println("Sum of “+num1+" and “+num2+" is "+result);
On execution, the sum of the two numbers is displayed. In this statement, the ‘+’ operator is used to concatenate two strings. But before concatenation, the integer values are converted to a string.
Besides, inputting integers, you can also input floating point numbers, strings etc. To input floating point number use the nextFloat () or nextDouble () method and to input a string use the next () or nextLine () method of Scanner object