Here’s a Java program to perform basic arithmetic operations (+
, -
, *
, /
, %
) based on the user’s choice for any two integers.
import java.util.Scanner;
public class ArithmeticOperations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input two integers
System.out.print(“Enter first number: “);
int a = sc.nextInt();
System.out.print(“Enter second number: “);
int b = sc.nextInt();
// Display operation choices
System.out.println(“\nChoose an operation:”);
System.out.println(“1. Addition (+)”);
System.out.println(“2. Subtraction (-)”);
System.out.println(“3. Multiplication (*)”);
System.out.println(“4. Division (/)”);
System.out.println(“5. Modulus (%)”);
System.out.print(“Enter your choice (1-5): “);
int choice = sc.nextInt();
// Perform operation based on choice
switch (choice) {
case 1:
System.out.println(“Result: ” + (a + b));
break;
case 2:
System.out.println(“Result: ” + (a – b));
break;
case 3:
System.out.println(“Result: ” + (a * b));
break;
case 4:
if (b != 0)
System.out.println(“Result: ” + ((double)a / b));
else
System.out.println(“Error: Division by zero”);
break;
case 5:
if (b != 0)
System.out.println(“Result: ” + (a % b));
else
System.out.println(“Error: Modulus by zero”);
break;
default:
System.out.println(“Invalid choice. Please enter a number from 1 to 5.”);
}
sc.close();
}
}
OUTPUT
Enter first number: 20
Enter second number: 5
Choose an operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Modulus (%)
Enter your choice (1-5): 3
Result: 100