20165218结对编程练习-四则运算

编程项目-四则运算

需求分析

  1. 实现一个带有用户界面的四则运算
  2. 可以选择运算符类型
  3. 可以键入需要运算的数
  4. 可以重复使用

设计思路

  1. 声明成员变量type为运算符类型
  2. 声明整型变量ABC为运算数及答案
  3. 声明String型变量Exit
  4. 键盘键入type及AB的值
  5. 通过switch语句进行计算
  6. 返回答案C的值
  7. 通过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();
        }
    }
}

测试结果

代码托管

posted @ 2018-04-15 23:40  zicerain  阅读(172)  评论(0编辑  收藏  举报