JavaDay04.练习1简易计算器

写一个简易计算器程序
界面如下:
—计算器—
1.加法
2.减法
3.乘法
4.除法
5.退出

要求完成以上5个功能,并且代码中要使用方法来架构,
必须要有的方法包括打印界面的方法,加减乘除4个方法,以及获取用户输入的方法…
整个功能要求连贯连续,直到用户选择退出,才可以正式退出程序.
提示:循环,判断,Scanner,方法定义…

import java.util.Scanner;
public class Calc {
    public static void main(String[] args) {
        start();
    }

    /**
     * 启动程序
     */
    public static void start() {
        for (; ; ) {
            showMenu();
            int choice = getInt("请选择: ");
            if (choice == 1) {
                //加法
                int n1 = getInt("请您输入被加数: ");
                int n2 = getInt("请您输入加数: ");
                int r = add(n1, n2);
                System.out.println(n1 + " + " + n2 + " = " + r);
            } else if (choice == 2) {
                //减法
                int n1 = getInt("请您输入被减数: ");
                int n2 = getInt("请您输入减数: ");
                int r = sub(n1, n2);
                System.out.println(n1 + " - " + n2 + " = " + r);
            } else if (choice == 3) {
                //乘法
                int n1 = getInt("请您输入被乘数: ");
                int n2 = getInt("请您输入乘数: ");
                int r = mut(n1, n2);
                System.out.println(n1 + " * " + n2 + " = " + r);
            } else if (choice == 4) {
                //除法
                int n1 = getInt("请您输入被除数: ");
                int n2 = getInt("请您输入除数: ");
                int r = div(n1, n2);
                System.out.println(n1 + " / " + n2 + " = " + r);
            } else if (choice == 5) {
                System.out.println("谢谢使用!");
                break;
            }
        }
    }

    /**
     * 打印主界面
     */
    public static void showMenu() {
        System.out.println("---计算器---\n" +
                "1.加法\n" +
                "2.减法\n" +
                "3.乘法\n" +
                "4.除法\n" +
                "5.退出\n" +
                "-------------");
    }

    /**
     * 定义方法来获取用户输入
     */
    public static int getInt(String message) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(message);
        return scanner.nextInt();
    }

    /**
     加减乘除
     */
    public static int add(int a, int b) {
        return a + b;
    }

    public static int sub(int a, int b) {
        return a - b;
    }


    public static int mut(int a, int b) {
        return a * b;
    }


    public static int div(int a, int b) {
        return a / b;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值