public class CalculatorSwitchCase
{
public static void main(String[] args)
{
double no1=10, no2=30;
char operator = '*';
double result;
// Use switch case to perform the selected operation
switch (operator)
{
case '+':
result = no1 + no2;
System.out.println("Result: " + result);
break;
case '-':
result = no1 - no2;
System.out.println("Result: " + result);
break;
case '*':
result = no1 * no2;
System.out.println("Result: " + result);
break;
case '/':
if (no2 != 0) {
result = no1 / no2;
System.out.println("Result: " + result);
}
else
{
System.out.println("Error: Division by zero is not allowed.");
}
break;
case '%':
if (no2 != 0)
{
result = no1 % no2;
System.out.println("Result: " + result);
}
else
{
System.out.println("Error: Modulus by zero is not allowed.");
}
break;
default:
System.out.println("Invalid operator. Please choose a valid operation.");
}
}
}
Result: 300.0
import java.util.Scanner;
public class CalculatorSwitchCase
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Take two numbers as input
System.out.print("Enter the first number: ");
double no1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double no2 = scanner.nextDouble();
// Ask the user to choose an operation
System.out.println("Choose an operation (+, -, *, /, %): ");
char operator = scanner.next().charAt(0);
double result;
// Use switch case to perform the selected operation
switch (operator)
{
case '+':
result = no1 + no2;
System.out.println("Result: " + result);
break;
case '-':
result = no1 - no2;
System.out.println("Result: " + result);
break;
case '*':
result = no1 * no2;
System.out.println("Result: " + result);
break;
case '/':
if (no2 != 0)
{
result = no1 / no2;
System.out.println("Result: " + result);
}
else
{
System.out.println("Error: Division by zero is not allowed.");
}
break;
case '%':
if (no2 != 0)
{
result = no1 % no2;
System.out.println("Result: " + result);
}
else
{
System.out.println("Error: Modulus by zero is not allowed.");
}
break;
default:
System.out.println("Invalid operator. Please choose a valid operation.");
}
// Close the scanner
scanner.close();
}
}
Enter the first number: 10 Enter the second number: 20 Choose an operation (+, -, *, /, %): + Result: 30.0
no1
and no2
).
+
, -
, *
, /
, %
).
+
): Adds no1
and no2
.
-
): Subtracts no1
from no2
.
*
): Multiplies no1
and no2
.
/
): Divides no1
by no2
. If no2
is zero, it displays an error message.
%
): Computes the remainder when no1
is divided by no2
.
scanner.close()
method is used to close the input stream and release resources.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.