Use Java to write a calculator, realize the function of addition, subtraction, multiplication and division, and be able to receive new data cyclically, through user interaction

public class HomeworkDemo {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);


        double result = 0;
        while (scanner.hasNextDouble()) {
    
    
            double i = scanner.nextDouble();
            String str = scanner.next();
            double j = scanner.nextDouble();

            switch (str) {
    
    
                case "+":

                    result = add(i, j);

                    System.out.println(result);
                    break;
                case "-":

                    result = minus(i, j);

                    System.out.println(result);
                    break;
                case "*":

                    result = multiply(i, j);

                    System.out.println(result);
                    break;
                case "/":if(j==0){
    
    
                    System.out.println("除数不能为零");
                    break;
                }else

                    result = divide(i, j);

                    System.out.println(result);
                    break;
            }if (str.equals("quit")){
    
    
                System.out.println("退出计算器");
                break;
            }


        }scanner.close();
    }

    //加
    public static double add ( double a , double b){
    
    
        return a + b;
    }//减
    public static double minus ( double a , double b){
    
    
        return a - b;
    }//乘
    public static double multiply ( double a , double b){
    
    
        return a * b;
    }//除
    public static double divide ( double a , double b){
    
    
        return a / b;
    }


}

Problems encountered: 1. Using scanner.hasNext as the boolean expression of while, leading to the failure to assign a value to the first number when a new set of data to be calculated is input, instead it jumps directly to the judgment of scanner.hasNext. So change the Boolean expression of while to scanner.hasNextDouble
2. When the divisor is zero, it will not only output "Divisor cannot be zero", but also output the value 0 assigned to result at the beginning and add break; then solve the problem.
3. Using the idea of ​​step-by-step solution, you can make a calculator that can do addition operations and a calculator that can do four arithmetic operations.

Guess you like

Origin blog.csdn.net/qq_43021902/article/details/113822261