所以我还在努力让这个计算器正常工作。关键是它不断询问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;
}
}