Java项目报错:运算符-对String、double类型参数未定义
Hey there, let's break down this error you're facing and fix it right away.
What's Causing the Error?
Your problematic code line is:
System.out.println("the result is: \n" + num1 - num2);
The root issue is Java's operator precedence rules. Operators like + (string concatenation) and - (subtraction) have the same precedence, so Java evaluates them from left to right.
Here's the play-by-play:
- First, Java runs
"the result is: \n" + num1— this turns the entire expression into aString(since you're concatenating a string with a number). - Next, it tries to do
[resulting String] - num2— but Java has no built-in way to subtract adoublefrom aString. That's exactly why you get the error message:The operator - is undefined for the argument type(s) String, double.
How to Fix It
You need to tell Java to calculate the subtraction before doing any string concatenation. Parentheses () have higher precedence than both + and -, so wrapping the arithmetic operation in parentheses will force Java to handle that part first.
Here's the corrected code:
System.out.println("the result is: \n" + (num1 - num2));
Now Java will first compute num1 - num2 (resulting in a double value), then concatenate that result to your string—no more errors!
内容的提问来源于stack exchange,提问作者AHMED MOKHTAR

