Java转换错误:意外类型。必需:变量,找到:值

Java转换错误:意外类型。必需:变量,找到:值,java,casting,Java,Casting,在Java中,我试图将int转换为double,然后再转换回int 我得到这个错误: unexpected type (double)(result) = Math.pow((double)(operand1),(double)(operand2)); ^ required: variable found: value 根据该代码: (double)(result) = Math.pow((double)(operand1),(doub

在Java中,我试图将int转换为double,然后再转换回int

我得到这个错误:

unexpected type
          (double)(result) =  Math.pow((double)(operand1),(double)(operand2));
          ^
  required: variable
  found:    value
根据该代码:

(double)(result) =  Math.pow((double)(operand1),(double)(operand2));
return (int)(result);

错误消息是什么意思?

调用Math.pow不需要将int转换为double:

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));
    }
}

让我们假设
结果
实际上是一个
双精度
,那么您只需执行以下操作

result = Math.pow((double)(operand1),(double)(operand2));
result = (int)Math.pow((double)(operand1),(double)(operand2));
现在,让我们假设
结果
实际上是
int
,然后您只需执行以下操作

result = Math.pow((double)(operand1),(double)(operand2));
result = (int)Math.pow((double)(operand1),(double)(operand2));
已更新

根据Patricia Shanahan的反馈,代码中有很多不必要的噪音。如果没有进一步的上下文,很难完整地进行注释,但是,将
操作数1
操作数2
显式区分为
双精度
是不太可能的(也是没有帮助的)。Java能够自己解决这个问题

Math.pow(operand1, operand2);

这个消息只是意味着你把语法搞乱了。强制转换需要在equals的右侧进行,而不是在分配给的变量前面。

Java代码:

double my_double = 5;
(double)(result) = my_double;  
将引发编译时错误:

The left-hand side of an assignment must be a variable
不允许对指定给的等号左侧的变量进行强制转换。代码的意思根本没有意义。您是否试图提醒编译器您的变量是双精度的?好像它还不知道?

您可能打算:

double result =  Math.pow((double)(operand1),(double)(operand2));
return (int)(result);
或等效但更简单地:

double result =  Math.pow((double)operand1,(double)operand2);
return (int)result;
甚至:

return (int)Math.pow((double)operand1,(double)operand2);

…如果
result
是一个
int
,为什么不将
pow
结果强制转换为
int
?我试过了,它说了同样的话。导致错误的问题是,您在赋值操作的左侧强制转换。施法需要紧靠等号的右边,在左边是双精度或双精度。这是一种有趣的方法,我想知道将
Math.pow
的结果施法到
int
(使用
(int)Math.pow
)和你的方法之间的区别是什么……事实证明,绝对没有嗯,没意思,莱西不是落选者,只有落选者有解释性的评论。但是,我不同意显式强制转换在Math.pow参数上加倍。@PatriciaShanahan这是OP的代码,但这不是借口。如果不知道操作数1
和操作数2
是什么,就很难进行评论。我将添加一个额外的注释如果double可以作为a的目标,则会有一些操作数类型可以工作,但不会。没有缩小原语转换会产生一个double,因此操作数1或操作数2的类型既不允许也不需要强制转换。