[英]Java casting error: unexpected type. required: variable, found: value
In Java, I am trying to cast an int into a double and then back an int. 在Java中,我试图将一个int转换为一个double,然后返回一个int。
I am getting this error: 我收到此错误:
unexpected type
(double)(result) = Math.pow((double)(operand1),(double)(operand2));
^
required: variable
found: value
From this code: 从此代码:
(double)(result) = Math.pow((double)(operand1),(double)(operand2));
return (int)(result);
What does the error message mean? 错误消息是什么意思?
You don't need to cast int to double in order to call Math.pow: 您无需将int转换为double即可调用Math.pow:
package test;
public class CastingTest {
public static int exponent(int base, int power){
return ((Double)Math.pow(base,power)).intValue();
}
public static void main(String[] arg){
System.out.println(exponent(5,3));
}
}
The message just means that you've messed up the syntax. 该消息仅表示您弄乱了语法。 The casting needs to go on the right hand side of the equals, not in front of the variable that you're assigning to.
强制转换需要位于等号的右侧,而不要位于您要分配给的变量的前面。
Let's assume that result
is actually a double
, then you would simply only need to do... 让我们假设
result
实际上是double
,那么您只需要做...
result = Math.pow((double)(operand1),(double)(operand2));
Now, let's assume that result
is actually int
, then you simple need to do... 现在,让我们假设
result
实际上是int
,那么您只需要做...
result = (int)Math.pow((double)(operand1),(double)(operand2));
Updated 更新
With feedback from Patricia Shanahan, there is a lot of unnecessary noise in the code. 有了Patricia Shanahan的反馈,代码中有很多不必要的噪音。 Without further context, it is difficult to comment entirely, but, it is unlikely (and unhelpful) to case
operand1
and operand2
explicitly to double
. 没有更多上下文,很难完全注释掉,但是将操作
operand1
和操作operand2
显式double
是不可能的(并且没有帮助)。 Java is capable of taking care of this by itself. Java能够自己解决这个问题。
Math.pow(operand1, operand2);
This code in Java: Java中的这段代码:
double my_double = 5;
(double)(result) = my_double;
Will throw an compile time error: 将抛出编译时错误:
The left-hand side of an assignment must be a variable
Casts are not allowed on a variable to the left of the equals sign being assigned to. 不允许对等号左侧的变量进行强制转换。 It doesn't even make sense what the code would mean.
这段代码意味着什么,甚至都没有意义。 Are you trying to remind the compiler that your variable is a double?
您是否要提醒编译器变量为double? As if it didn't already know?
好像还不知道?
you probably intend: 您可能打算:
double result = Math.pow((double)(operand1),(double)(operand2));
return (int)(result);
or equivalently but more simply: 或同等但更简单地:
double result = Math.pow((double)operand1,(double)operand2);
return (int)result;
or even: 甚至:
return (int)Math.pow((double)operand1,(double)operand2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.