【问题标题】:how to fix referencing a non-static method in a static context [duplicate]如何修复在静态上下文中引用非静态方法[重复]
【发布时间】:2019-10-19 01:12:55
【问题描述】:

这是我的 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 行?我觉得有点不一样。

【问题讨论】:

  • new RandomSequence().firstTenTerms()
  • 您需要使用new 创建一个RandomSequence 的对象,然后您可以使用它调用.firstTenTerms()static 基本上意味着您不需要从类中创建对象即可使用该方法。
  • 提示:几乎所有你梦寐以求的“新手”问题......以前都被问过。因此,请在发布问题之前进行一些研究。通常,写一个新问题比在互联网上找到现有问题的解决方案花费的时间更多。只需将错误消息输入谷歌,然后就可以了。

标签: java methods printing reference static


【解决方案1】:

您将 firstTenTerms() 方法声明为实例方法,因此您必须像这样创建 RandomSequence 实例:

new RandomSequence().firstTenTerms();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    相关资源
    最近更新 更多