Java program for a calculator using switch case

Java program for a calculator using switch case. In Java programming, build a simple calculator program. This is a straightforward calculator. Basic operations such as add, sub, mul, and div will be performed.

The java basic calculator software is intended only for beginners who want to learn how to use the java programming language to perform calculations. It is self-evident that a calculator can relieve the consumer of the need to perform mental calculations and rely on paper

import java.util.Scanner;
public class Main
{
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 operators");
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("operator is correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}

 

Output

Enter two numbers 4 5 9

What is switch case and uses of the switch case in java

In Java, the switch case is used to pick one of the multiple code blocks to execute. The control breaks out of the switch block when java reaches the break keyword. 

When this keyword is encountered, code execution is halted, and case testing within the block is completed after a match is discovered. No. Because a case must be a constant expression, this is not feasible. 

The major advantages of employing a switch are that it improves clarity by avoiding otherwise repeated coding and, in many situations, allows for quicker execution through simpler compiler optimization. A switch must include at least 257 case statements, according to Standard C.

Default

Access modifiers are a Java default keyword. By default, if you don’t apply any access modifiers to variables, methods, constructors, or classes, the default access modifier is used.

Break

There are two uses for the break statement in the Java programming language. When a break statement is reached within a loop, the loop is instantly stopped, and program control is resumed at the next statement after the loop.

Return

The control of the program is returned to the method’s caller when a return statement is used. Every Java method declares a return type, which is required for all Java methods. A primitive type, such as int, float, or double, a reference type, or a void type, can be used as a return type.