更新时间:2022-04-15 09:42:13 来源:极悦 浏览1031次
一个基本的计算器能够加、减、乘或除两个数字。这是使用开关盒完成的。演示这一点的程序如下
例子
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 case 用于对两个数字执行指定的操作。如果输入的操作员不正确,则会显示错误消息。演示这一点的代码片段如下
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);
0基础 0学费 15天面授
Java就业班有基础 直达就业
业余时间 高薪转行
Java在职加薪班工作1~3年,加薪神器
工作3~5年,晋升架构
提交申请后,顾问老师会电话与您沟通安排学习