我试图在Java上编写一个计算器,但在switch语句中它将操作作为一个字符串,我如何在一个动作中对其进行转换?
switch(op) {
case 1: operation = "res= a + b";
break;
case 2: operation = "res = a - b";
break;
case 3: operation = "res = a * b";
break;
case 4: operation = "res = a / b";
break;
}
System.out.println(operation);
如果我删除引号,它说我还没有初始化变量。选择手术后会询问他们。
答案 0 :(得分:0)
Don't perform the operation until you have the arguments:
import static java.lang.Integer.*;
import java.util.*;
class t1 {
static void calc(Scanner in) {
System.out.print("Operation: ");
int op = in.nextInt();
System.out.print("a: ");
int a = in.nextInt();
System.out.print("b: ");
int b = in.nextInt();
int res = 0;
switch(op) {
case 1:
res = a + b;
break;
case 2:
res = a - b;
break;
case 3:
res = a * b;
break;
case 4:
res = a / b;
break;
default:
System.out.println("Invalid operation");
System.exit(-1);
}
System.out.println(res);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
while (true) {
calc(in);
}
}
}
You could verify the operation before asking for the operands, with an additional switch statement.
There are ways to set the operation before obtaining the operands, but it's best to learn to walk before you run.