编程项目-四则运算
需求分析
- 实现一个带有用户界面的四则运算
- 可以选择运算符类型
- 可以键入需要运算的数
- 可以重复使用
设计思路
- 声明成员变量type为运算符类型
- 声明整型变量ABC为运算数及答案
- 声明String型变量Exit
- 键盘键入type及AB的值
- 通过switch语句进行计算
- 返回答案C的值
- 通过Exit判断是否结束程序,若否,回到第5部
代码实现
import java.util.Scanner;
import java.util.Random;
public class FourOperations {
//选择所需要的四则运算
public static void main(String[] args) {
int type;
int A, B, C;
String Exit = "n";
Scanner scanner = new Scanner(System.in);
while (Exit.equalsIgnoreCase("n")) {
System.out.println("==========整数的四则运算==========");
System.out.println("请选择要进行的四则运算");
System.out.print("1(+) 2(-) 3(×) 4(÷) : ");
type = scanner.nextInt();
//进行四则运算
switch (type) {
case 1:
System.out.print("请输入两个整数:");
A = scanner.nextInt();
B = scanner.nextInt();
C = A + B;
System.out.println(A + " + " + B + " = " + C);
break;
case 2:
System.out.print("请输入两个整数:");
A = scanner.nextInt();
B = scanner.nextInt();
C = A - B;
System.out.println(A + " - " + B + " = " + C);
break;
case 3:
System.out.print("请输入两个整数:");
A = scanner.nextInt();
B = scanner.nextInt();
C = A * B;
System.out.println(A + " × " + B + " = " + C);
break;
case 4:
System.out.print("请输入两个整数:");
A = scanner.nextInt();
B = scanner.nextInt();
C = A / B;
System.out.println(A + " ÷ " + B + " = " + C);
break;
//default排错
default:
System.out.print("输入的运算代表数字错误!");
}
//优化设计
System.out.print("退出程序?(y/n): ");
Exit = scanner.nextLine();
Exit = scanner.nextLine();
}
}
}
测试结果