如何在静态上下文中修复对非静态方法的引用

时间:2019-06-03 13:08:00

标签: java methods printing reference static

这是我的RandomSequence类代码:     导入java.util。*;

public class RandomSequence implements Sequence
{
   private ArrayList<Double> random;

   public RandomSequence()
   {
      random = new ArrayList<Double>(); 
   }

   public List<Double> firstTenTerms()
   {
      if(random.size()!=0)
      {
         while(random.size()>0)
         {
            random.remove(random.size()-1);
         }
      }

      for(int k=0; k<10; k++)
      {
         random.add((int)(Math.random()*10)+1.0);
      }
      return random;
   }
}

这是我的驱动程序类:     导入java.io. ;     导入java.util。;

public class SequenceMain
{
   public static void main(String[] args) throws Exception
   {
      File f = new File("sequence1.txt");
      Scanner scan = new Scanner(f);
      System.out.println("I'm going to generate a random \"sequence\" and sort it. Here're the first 10 terms of sequence.");
      System.out.println(RandomSequence.firstTenTerms());
    }
    public void ascendingSort(List<Double> alist)
    {
      Collections.sort(alist);
    }

}

运行驱动程序类时,我会不断收到以下错误消息:

SequenceMain.java:13: error: non-static method firstTenTerms() cannot be referenced from a static context
      System.out.println(RandomSequence.firstTenTerms());
SequenceMain.java:18: error: non-static method ascendingSort(List<Double>) cannot be referenced from a static context
  ascendingSort(alist);

似乎已经有很多与非静态方法和静态上下文等有关的问题,我已经看过其中一些文章,但是坦率地说,我现在比以前更加困惑。

更新:感谢您在第13行给我的反馈,但是我该如何解决18行?我觉得有点不同。

1 个答案:

答案 0 :(得分:0)

您已将firstTenTerms()方法声明为实例方法,因此必须创建如下的RandomSequence实例:

new RandomSequence().firstTenTerms();