我收到此错误;二元运算符的坏操作数类型' - ' 所有其他操作都有效...当我通过//和/ * * /等注释省略减法时有人可以帮忙吗?
这是顺便提一下的代码;例外是在减法线上。
public class Calculator {
/*
*use 'javac Calculator.java' to compile;
*use 'jar cvf Calculator.jar Calculator.class' for jar;
*use 'java Calculator' to run;
*/
public static void main(String []args) {
String NewName
Scanner user_input = new Scanner( System.in );
System.out.println("Type your name please.");
NewName = user_input.next();
System.out.println("");
System.out.println("Hello " + NewName + ".");
System.out.println("I am Hunter's java calculator program.");
System.out.println("");
//mathematical input
String operator;
float cal1, cal2;
System.out.println("Type a Number...");
cal1 = user_input.nextFloat();
System.out.println("");
System.out.println("Type another Number...");
cal2 = user_input.nextFloat();
System.out.println("");
Scanner opt = new Scanner(System.in);
System.out.println("Enter an operator");
operator = opt.next();
//operation decisions
if (operator.equals("+")){
System.out.println("The answer is " + cal1+cal2 + ".");
}
if (operator.equals("-")){
System.out.println("The answer is " + cal1-cal2 + ".");
}
if (operator.equals("/")){
System.out.println("The answer is " + cal1/cal2 + ".");
}
if (operator.equals("*")){
System.out.println("The answer is " + cal1*cal2 + ".");
}
}
}
答案 0 :(得分:5)
你需要括号:
System.out.println("The answer is " + (cal1-cal2) + ".");
否则你拥有的东西被视为
System.out.println(("The answer is " + cal1) - (cal2 + "."));
由于您无法减去字符串而无效。
为什么你的其他运营商没有错误?好吧,*
和/
具有更高的优先级,因此这些正在按预期工作。另一方面,+
被重载以连接字符串:
System.out.println("The answer is " + cal1+cal2 + "."); // concatenates, doesn't add
例如,如果call1
为1
且call2
为2
,则结果为:
The answer is 12.
这不是你想要的。同样,这可以用括号解决。