问题描述
我想输入一个int来获取第一个数字,然后使用字符串来获取运算符,并使用另一个int来获取第二个数字。用户应输入10 + 20之类的内容。
,但是一旦我输入 +,我为什么会出错?
i want to input a int to get first number then use a string to get the operator and another int for the second number. user should input some thing like 10+20.but as soon as i enter the "+" then i get an error why?
cuz如果我手动将值添加到sum.calc中,它将起作用();我自己喜欢sum.calc(12, +,24);然后它会失败36
cuz it works if i manually add the values into the sum.calc(); myself like sum.calc(12, "+", 24); then it works ill get 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();
将此扫描程序前进到当前行之外,并返回被跳过的输入。因此,如果您输入的是20,+和24,则方法 calc
会得到20,24,null。
Try using input.next();
instead of input.nextLine();
Because input.nextLine();
advances this scanner past the current line and returns the input that was skipped. so if your input was 20, +, and 24, your method calc
would get 20,24,null.
这篇关于我不能让我的计算器工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!