In this Java program, we will take an integer input from the user and perform addition on those numbers.
The program utilizes the Scanner class from the java.util package to read input from the user.
In this program
- We import the java.util.Scanner class to use for user input.
- We declare variables for the two numbers to be added (firstNumber and secondNumber) and a variable to store the result (sum).
- We create a Scanner object named scanner to read input from the user.
- We display a message to prompt the user to enter the first number using System.out.print.
- We use scanner.nextInt() to read an integer from the user, which is then assigned to the firstNumber variable.
- We repeat the process to get the second number.
- We calculate the sum of the two numbers and store it in the sum variable.
- Finally, we display the result using System.out.println and close the Scanner object to release resources.
import java.util.Scanner;
public class AdditionProgram {
public static void main(String[] args) {
int a, b, ans;
Scanner scanner = new Scanner(System.in);
System.out.println("Addition Program");
System.out.print("Enter 1st number: ");
a = scanner.nextInt();
System.out.print("Enter 2nd number: ");
b = scanner.nextInt();
ans = a + b;
System.out.println("Addition is: " + ans);
scanner.close();
}
}
Follow Us