Java计算器不会输出答案

时间:2013-05-29 19:24:21

标签: java function calculator do-while

所以我仍然试图使这个计算器正常工作。重点在于它一直要求y值和操作符,直到用户输入“q”。唯一的事情是它不会返回值,一旦我输入q它就不会停止。它只是在事后要求y值。下面是我不断得到的输出的一个例子。我是否必须创建一个额外的变量来保存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;
}

}

2 个答案:

答案 0 :(得分:1)

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

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

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

if (Op.equalsIgnoreCase("q")){
    ...
}

答案 1 :(得分:0)

==和!=运算符不适用于字符串。你必须使用Op.equals(" ......")代替。