方法中的math.pow导致错误

时间:2016-10-12 18:21:02

标签: java methods

任何人都可以解释为什么以下方法不起作用并返回以下错误消息:“线程中的异常”主“java.lang.RuntimeException:无法编译的源代码 - 错误的树类型:”

class Example01 {
   public static void main(String[] args) {
     System.out.println(myExp(2));
   }
     double myExp(int x) {
     return Math.pow(x,2);
     }
}

我认为可能是在Math.pow中使用int变量但是我没有设置方法就这样尝试了它并且它工作正常:

System.out.println(Math.pow(2,2));

有人可以对方法无法返回结果的原因有所了解吗?

非常感谢, 维拉德

4 个答案:

答案 0 :(得分:0)

将方法double myExp(int x)更改为static double myExp(int x)

答案 1 :(得分:0)

方法double myExp(int x)应该是静态的。

答案 2 :(得分:0)

你必须声明myExp static。

 static double myExp(int x) {
    return Math.pow(x,2);
 }

或者您可以实例化Example01类并调用该函数。

class Example01 {
  public static void main(String[] args) {
    Example01 ex = new Example01();
    System.out.println(ex.myExp(2));
  }
  double myExp(int x) {
    return Math.pow(x,2);
  }
}

答案 3 :(得分:0)

在java中,所有非静态方法都是实例方法,即它们需要调用实例或对象。要么声明myExp(int x)方法静态,即static double myExp(int x),要么实例化您的类以创建对象,然后在其上调用myExp(int x)

 class Example01 {
 public static void main(String[] args) {
Example01 example = new Example01();
System.out.println(example.myExp(2));
}
double myExp(int x) {
return Math.pow(x,2);
}
}