4

所以我还在努力让这个计算器正常工作。关键是它不断询问y值和运算符,直到用户输入“q”。唯一的问题是它不会返回值,并且一旦我输入 q 它就不会停止。之后它只是不断要求任何价值。这是我不断得到的输出示例。我是否必须创建一个额外的变量来保存 y 值来更新它并在之后打印出来?

X: 5 Y: 5 Op: + Y: 5 Op: q Y:

    Scanner keyboard = new Scanner(System.in);

    double x;
    double y;
    String Op;

    System.out.print("X: ");
    x = keyboard.nextDouble();

    do{
        System.out.print("Y: ");
        y = keyboard.nextDouble();
        keyboard.nextLine();
        System.out.print("Op: ");
        Op = keyboard.nextLine();

        if(Op == "+"){
            double result = sum(x,y);
            System.out.println(result);
            }
        else if(Op == "/"){
            double division = div(x,y);
            System.out.println(division);
            }
        else if(Op == "-"){
            double subtraction = sub(x,y);
            System.out.println(subtraction);
            }
        else if(Op == "*"){
            double times = mult(x,y);
            System.out.println(times);
            }
        else if(Op == "q")
            System.out.print("Your last result was: " +y);
    }while(Op != "q");

}   
public static double sum (double a, double b){
    double res = a + b;
    return res;
}
public static double div (double a, double b){
    if(b==0){
        System.out.println("Error, attempted a division by zero");
        return b;
        }
    double divide = a/b;
    return divide;
}
public static double sub (double a, double b){
    double minus = a-b;
    return minus;
}
public static double mult (double a, double b){
    double times = a*b;
    return times;
}

}

4

2 回答 2

1

对于String比较,您需要使用方法equalsequalsIgnoreCase

==运算符仅适用于 char、int、byte 等原语。对于 String 等对象,则需要使用比较方法。

转换为正确的方法将解决您的问题。例子

if (Op.equalsIgnoreCase("q")){
    ...
}
于 2013-05-29T19:27:08.463 回答
0

== 和 != 运算符不适用于字符串。您必须改用 Op.equals("...") 。

于 2013-05-29T19:29:39.610 回答