Java Calculator错误的操作员提示

时间:2017-10-10 16:39:46

标签: java calculator

我有一个计算器类,我希望操作输入特定于这些字符串“+, - ,/,*”,如果不是,我想打印一条消息再次进入操作员。 并且,如果有人会减少我的代码,请执行此操作。感谢

这是我的代码

import java.util.Scanner;

公共类Calculator1 {

public static void main(String[] args) {    
    Scanner num = new Scanner(System.in);
    String operation;
    Double fnum, lnum, answer;
    System.out.println("Enter first Number: ");
    while (!num.hasNextDouble())
    {
        num.next();
        System.out.print("Enter first Number: ");
    }
    fnum = num.nextDouble();
    System.out.println("Enter Operation: ");
    //HERE IM BEING CONFUSED
    while (!num.equals("+, -, /, *"))
    {
        num.next();
        System.out.print("Enter Operator: ");
    }
    operation = num.next();
    //End
    System.out.println("Enter Second Number: ");
    while (!num.hasNextDouble())
    {
        num.next();
        System.out.print("Enter Second Number: ");
    }
    lnum = num.nextDouble();




    switch (operation) {
    case "+":
        answer = fnum + lnum;
        System.out.print("Equals= " + answer);
        break;
    case "-":
        answer = fnum - lnum;
        System.out.print("Equals= " + answer);
        break;
    case "*":
        answer = fnum * lnum;
        System.out.println("Equals= " + answer);
        break;
    case "/":
        answer = fnum / lnum;
        System.out.println("Equals= " + answer);
        break;
    default:
        System.out.println("wrong operator");
        break;


    }
}

}

1 个答案:

答案 0 :(得分:1)

这是一种使用SWITCH语句的运算符的方法。

public static void main(String[] args) {

    Scanner num = new Scanner(System.in);
    double v1,v2;
    String v3;

    System.out.print("Enter first number: ");
    v1 = num.nextDouble();
    System.out.print("Enter second number: ");
    v2 = num.nextDouble();
    System.out.print("Enter operation [+]   [-]   [*]   [/]: ");
    v3 = num.next();

    System.out.println( ("+".equals(v3) ) ? Operators.ADD.calculate(v1, v2) : "....");

    }

public enum Operators {
    ADD;

    double calculate(double x, double y) {
        switch (this) {
            case ADD:
                return x + y;
            default:
                throw new AssertionError("Unknown operations " + this);
        }
    }

}