---
title: 简单的Java加减乘除计算器(适合新手)
date: 2020-05-30 22:59:13
tags:
- Java
- 代码
categories:
- Java练习
---

本人Java新手一枚，刚学完Java数据类型、流程控制、数组、方法等基础语法知识。

尝试写了一个简单的计算器，实现了加减乘除功能，并可以循环接收数据。

代码有待改进，希望各位大佬多多指点 :beers:

<!-- more -->

```java
public class calculator {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(true){
            System.out.println("请输入需要计算的第一个数字");
            double a = in.nextDouble();
            System.out.println("请输入需要计算的第二个数字");
            double b = in.nextDouble();
            while(true) {
                System.out.println("请输入运算方式(+ - * /)");
                String operation = in.next();
                switch (operation) {
                    case "+":
                        System.out.println(add(a,b));
                        break;
                    case "-":
                        System.out.println(subtraction(a, b));
                        break;
                    case "*":
                        System.out.println(multiply(a, b));
                        break;
                    case "/":
                        System.out.println(division(a, b));
                        break;
                    default:
                        System.out.println("输入不正确，请重新输入");
                }
                break;
            }
            while (true) {
                System.out.println("是否继续使用? " + "YES/NO");
                String choose = in.next();
                if (choose.equals("YES")) {
                    break;
                } else if (choose.equals("NO")) {
                    System.out.println("欢迎下次使用，再见");
                    return;
                } else {
                    System.out.println("输入不正确，请重新输入");
                }
            }
        }
    }
    //加
    private static double add(double a,double b){
        return a+b;
    }
    //减
    private static double subtraction(double a,double b){
        return a-b;
    }
    //乘
    private static double multiply(double a,double b){
        return a*b;
    }
    //除
    private static double division(double a,double b){
        if(b==0){
            System.out.println("被除数不能为0");
            return 0 ;
        }
        return a/b;
    }
}
```