我不能让我的计算器工作

i cant get my calculator to work

我想输入一个 int 来获取第一个数字,然后使用一个字符串来获取运算符,另一个 int 来获取第二个数字。用户应该输入 10+20 之类的东西。 但是我一输入“+”就收到错误消息,为什么?

因为如果我手动将值添加到 sum.calc();我自己喜欢 sum.calc(12, "+", 24);然后它工作得不好得到 36

PART 1:
import java.util.Scanner;
public static void main(String[] args) {
    math sum = new math();
    Scanner input = new Scanner(System.in);
    double a = input.nextDouble();
    String b = input.nextLine();
    double c = input.nextDouble();
    sum.calc(a, b, c);
    input.close();
}


PART 2:
public class math {
public void calc(double a, String b, double c){
    double t;
    switch(b){
    case "+":
        t = a + c;
        System.out.println(a+" + "+c+" = "+t);
        break;
    case "-":
        t = a - c;
        System.out.println(a+" - "+c+" = "+t);
        break;
    case "*":
        t = a * c;
        System.out.println(a+" * "+c+" = "+t);
        break;
    case "/":
        t = a / c;
        System.out.println(a+" / "+c+" = "+t);
        break;
    }
}
}

尝试使用 input.next(); 而不是 input.nextLine(); 因为 input.nextLine(); 使此扫描器前进到当前行和 returns 被跳过的输入。因此,如果您的输入是 20、+ 和 24,您的方法 calc 将得到 20,24,null.

input.next() 代替 input.nextLine() 工作 strings.Try out