Java Program with Output
■ Java Program:
import java.util.Scanner;
class p2
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter which arithmatic operation you want to perform: ");
String opration = scanner.nextLine();
System.out.print("Enter first number: ");
int first_number = scanner.nextInt();
System.out.print("Enter second number: ");
int second_number = scanner.nextInt();
int result = 0;
if(opration.contains("add"))
{
result = first_number + second_number;
System.out.println("The result of addition is: " + result);
}
else if(opration.contains("sub"))
{
result = first_number - second_number;
System.out.println("The result of subtraction is: " + result);
}
else if(opration.contains("multi"))
{
result = first_number * second_number;
System.out.println("The result of multiplication is: " + result);
}
else if(opration.contains("div"))
{
if(second_number != 0) {
result = first_number / second_number;
System.out.println("The result of division is: " + result);
} else {
System.out.println("Division by zero is not allowed.");
}
}
else
{
System.out.println("Invalid operation. Please enter add, subtract, multiply, or divide.");
}
scanner.close();
}
}
■ Program Output:
--- Sample Outputs ---
1) Operation: add
Enter first number: 10
Enter second number: 5
Output → The result of addition is: 15
2) Operation: sub
Enter first number: 20
Enter second number: 8
Output → The result of subtraction is: 12
3) Operation: multi
Enter first number: 7
Enter second number: 6
Output → The result of multiplication is: 42
4) Operation: div
Enter first number: 40
Enter second number: 5
Output → The result of division is: 8
5) Operation: div
Enter first number: 10
Enter second number: 0
Output → Division by zero is not allowed.
6) Operation: xyz
Enter first number: 5
Enter second number: 3
Output → Invalid operation. Please enter add, subtract, multiply, or divide.