Using a switch statement, write a program that prompts the user for a numeric code and two operands. The numeric codes of 1, 2, 3, and 4 represents addition, subtraction, multiplication, and division respectively. Before division, your program should check whether the second operand is not zero. If it is, it should display “Division by zero not allowed” to the screen.
import java.util.Scanner;
public class MaximumValue {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Code: ");
int code = in.nextInt();
System.out.print("Operand 1: ");
int operand1 = in.nextInt();
System.out.print("Operand 2: ");
int operand2 = in.nextInt();
double result;
switch (code) {
case 1:// addition
{
result = operand1 + operand2;
System.out.println("Addition result = " + result);
}
break;
case 2:// subtraction
{
result = operand1 - operand2;
System.out.println("Subtraction result = " + result);
}
break;
case 3:// multiplication
{
result = operand1 * operand2;
System.out.println("Multiplication result = " + result);
}
break;
case 4:// division
{
if (operand2 != 0) {
result = operand1 / operand2;
System.out.println("Division result= " + result);
} else {
System.out.println("Division by zero not allowed");
}
}
break;
}
in.close();
}
}
Comments
Leave a comment