为什么我从另一个类调用此方法时遇到问题?

时间:2012-01-13 15:44:44

标签: java static

我是八年级学生,在java项目上有一个紧迫的截止日期。我已经准备好了我的GUI,除了我需要从两个文本字段中取两个值,并在按下按钮时将它们发送到另一个类中的方法。我无法调用我需要的方法。所有重要的代码都在下面。

尝试调用该方法的代码:

 private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         

    String Ntextfield = NumberTextField.getText();
    n = Integer.parseInt(Ntextfield);

    String Rtextfield = RateTextField.getText();
    r = Integer.parseInt(Rtextfield);
    //call PermMath class
    PermMath doTheMath = new PermMath();
    doTheMath.permutations(int n, int r);
}  

我试图打电话的方法:

class PermMath {
  static long factorial(int num){
      //other code is here
  }
  static long permutations(int n, int r){
        //code I want to call is here
  }
}

4 个答案:

答案 0 :(得分:5)

您的提示是static关键字。了解它的含义及其运作方式。

此外,您甚至在声明变量之前就使用变量nr

n = Integer.parseInt(Ntextfield); 

应该在您完成int n = 0;之后的事情。

在调用方法时,不要声明参数。以下是错误的。

doTheMath.permutations(int n, int r);

相反,你会做类似

的事情
doTheMath.permutations(n, r);

答案 1 :(得分:1)

在我看来,你有两个错误:

  1. 您正在传递两个名为nr的临时整数,而不是传递您在GoButtonActionPerformed函数中先前修改过的两个整数。
  2. permutations函数是静态的,因此无需实际创建PermMath类的实例。
  3. 将函数调用更改为:

    PermMath.permutations(n, r);
    

答案 2 :(得分:1)

请注意,如果PermMath位于另一个包中,而不是定义GoButtonActionPerformed(...)的类,则由于方法上缺少public访问修饰符甚至是类。

顺便说一下,在Java方法名称中应该以小写后者开头。虽然您的风格是有效的,但遵循惯例的代码使其他Java开发人员更容易阅读您的代码。

另一件事:你不使用permutations(...)的返回值。这可能没有意图。

答案 3 :(得分:0)

您已在static类中声明了PermMath个方法 - 这些方法不需要调用类的实例化。你只需用:

打电话给他们
PermMath.permutations(n,r);

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

上查看此曲目