In: Computer Science
Language: Java(Netbeans)
Implement a simple calculator.
*** I Kindly request you to Please provide a positive
rating******
Source code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
// nextDouble() reads the next double from the
keyboard
double num1 = sc.nextDouble();
double num2 = sc.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = sc.next().charAt(0);
double result;
switch(operator) // switch cases for the calculator
operations
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
// operator doesn't match any case constant (+, -, *,
/)
default:
System.out.printf("Error! operator is not correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", num1, operator, num2,
result);
}
}
output 1
Enter two numbers: 7
4
Enter an operator (+, -, *, /): -
7.0 - 4.0 = 3.0
output2:
Enter two numbers: 8
56
Enter an operator (+, -, *, /): +
8.0 + 56.0 = 64.0
output 3:
Enter two numbers: 45
6
Enter an operator (+, -, *, /): /
45.0 / 6.0 = 7.5
output 4:
Enter two numbers: 12
8.3
Enter an operator (+, -, *, /): *
12.0 * 8.3 = 99.6