基本计算器能够对两个数字进行加,减,乘或除运算。这是使用开关盒完成的。演示此的程序如下所示-
import java.util.Scanner; public class Calculator { public static void main(String[] args) { double num1; double num2; double ans; char op; Scanner reader = new Scanner(System.in); System.out.print("Enter two numbers: "); num1 = reader.nextDouble(); num2 = reader.nextDouble(); System.out.print("\nEnter an operator (+, -, *, /): "); op = reader.next().charAt(0); switch(op) { case '+': ans = num1 + num2; break; case '-': ans = num1 - num2; break; case '*': ans = num1 * num2; break; case '/': ans = num1 / num2; break; default: System.out.printf("Error! Enter correct operator"); return; } System.out.print("\nThe result is given as follows:\n"); System.out.printf(num1 + " " + op + " " + num2 + " = " + ans); } }
输出结果
Enter two numbers: 10.0 7.0 Enter an operator (+, -, *, /): - The result is given as follows: 10.0 - 7.0 = 3.0
现在让我们了解上面的程序。
从用户处获得两个数字以及运算符。证明这一点的代码片段如下-
double num1; double num2; double ans; char op; Scanner reader = new Scanner(System.in); System.out.print("Enter two numbers: "); num1 = reader.nextDouble(); num2 = reader.nextDouble(); System.out.print("\nEnter an operator (+, -, *, /): "); op = reader.next().charAt(0);
开关盒用于对两个数字执行指定的操作。如果输入的运算符不正确,则会显示错误消息。证明这一点的代码片段如下所示-
switch(op) { case '+': ans = num1 + num2; break; case '-': ans = num1 - num2; break; case '*': ans = num1 * num2; break; case '/': ans = num1 / num2; break; default: System.out.printf("Error! Enter correct operator"); return; }
最后,打印结果。证明这一点的代码片段如下所示-
System.out.print("\nThe result is given as follows:\n"); System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);