Java 计算器抛出 - 二元运算符的错误操作数类型 '-' -

标签 java operand

我收到这个错误;二元运算符“-”的错误操作数类型 所有其他操作都有效……当我通过//和/* */之类的注释省略减法时;有人可以帮忙吗?

顺便说一句,这是代码;异常(exception)是在减法线上。

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 + ".");
        }

}
}

最佳答案

你需要括号:

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

例如,如果call11call22,则结果为:

The answer is 12.

这不是你想要的。同样,这可以用括号解决。

关于Java 计算器抛出 - 二元运算符的错误操作数类型 '-' -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22583188/

相关文章:

C++ 没有运算符 ">>"匹配这些操作数(<string> 包含在 header 中)

java - apache avro 中的 mapred 和 mapreduce 包有什么区别?

java - 无效的 UTF-8 起始字节 0x8b(位于字符 #2,字节 #-1)

java - 试图让文本文件的每一行成为一个数组列表

sql - Postgres |带 OR 条件的 IF 语句

c++ - 运算符重载错误: no match for 'operator>>'

java - Jboss EAP6 和 Weblogic 11 XML 响应之间的差异

java - Maven 私有(private)依赖

python - 为什么返回 Nonetype?

python - 在 Python 中将 IF、AND、OR 与 EQUAL 操作数一起使用