switchcase programs in java
Answers
Syntax : Switch Case in Java Programming. It is alternative to else-if ladder. Switch Case Syntax is similar to – C/C++ Switch. Switch allows you to choose a block of statements to run from a selection of code, based on the return value of an expression.
Answer:
Switch case statement program in Java
Explanation:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
double first = reader.nextDouble();
double second = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = reader.next().charAt(0);
double result;
switch(operator)
{
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
default:
System.out.printf("Error! operator is not correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}