【问题标题】:Cant call a method in same java class不能在同一个java类中调用方法
【发布时间】:2016-10-02 12:38:24
【问题描述】:

我已经很久没有写过java了,我知道我的问题很简单,但我一辈子都无法弄清楚错误。

我正在尝试使用以下代码查找数组中的最小数字。该算法是正确的,但是在最后一个打印语句中尝试使用它时出现错误

package runtime;

import java.util.ArrayList;

public class app {


/**
 * @param args the command line arguments
 */

public int findSmallElement(ArrayList<Integer> num)
{
    int smElement; 
    smElement= num.get(0);
    for(int i=0; i<num.size() ; i++)
        if(num.get(i) < smElement)
            smElement=num.get(i);
    return smElement;
 }

public static void main(String[] args) {


    ArrayList<Object> num = new ArrayList<Object>();



    num.add(100);
    num.add(80);
    num.add(40);
    num.add(20);
    num.add(60);

    System.out.println("The size of the list is " +num.size());
    System.out.println(num.findSmallElement());

}

}

【问题讨论】:

    标签: java arraylist methods


    【解决方案1】:

    您试图在没有此方法的 ArrayList 变量/对象上调用您的方法,而您却想在您自己的类的实例上调用它。你应该将你的数组列表传递给这个方法。

    另一种选择是使您的方法静态并简单地自行调用它,再次传入数组列表。

    //  add the static modifier
    public static int findSmallElement(ArrayList<Integer> num)
    

    然后像这样调用:

    // pass the ArrayList into your findSmallElement method call
    int smallestElement = findSmallElement(num);
    // display the result:
    System.out.println("smallest element: " + smallestElement);
    

    【讨论】:

      【解决方案2】:

      ArrayList 没有有一个findSmallElement 方法。将您的方法设为static 并在num 中调用它

      System.out.println(findSmallElement(num));
      

      public static int findSmallElement(ArrayList<Integer> num)
      

      【讨论】:

        【解决方案3】:

        您可以创建一个对象并通过它调用它,而不是像上面提到的所有其他方法一样使您的方法成为静态方法,我认为这更方便

        App app = new App();
        int smallestElement = app.findSmallElement(sum);
        System.out.println("smallest element: " + smallestElement);
        

        我不太确定,但我认为这可行。

        【讨论】:

          【解决方案4】:

          当从static 上下文调用时,它应该调用另一个static

          所以只需将您的功能更改为 static 就像:

          public static int findSmallElement(ArrayList<Integer> num){...}
          

          提示:当您尝试使用来自非静态函数的全局静态变量时,还可以尝试看看发生了什么。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多