DLL实现&不能进行静态引用错误。

问题描述 投票:0回答:1

嗨,我得到一个错误信息 "不能做静态引用到非静态字段"。

在下一段代码的粗体行中,我不知道如何修复它,我对链接列表的实现是否正确,我知道我希望它是一个双链接列表。

import java.util.Scanner;
import java.util.LinkedList;
import java.lang.Number;
public class chainLadder {
    static Scanner s = new Scanner (System.in);

    public   LinkedList<Object> readData() {
         LinkedList<Object> listData = new LinkedList();

         Integer cost=0;
        
        System.out.println("how many years are you calculating");
            int numY=s.nextInt();
while(numY!=0) {    
    
 
     int i =1;
         System.out.println("please Enter the year"+i+" to calculate from ");
             String year = s.next();
                     listData.add(year);
                     listData.add(">"); // what comes after is the cost and before is the year

                     System.out.println("enter the costs of year"+year+"/n  enter ( -1 ) when done ");

                     while(cost != -1) {
                         cost = s.nextInt();
                         if(cost == -1)
                             break;
                         listData.add(cost);
                         System.out.println("next");
}
                     listData.add("<"); // what comes before is the cost and after  is the year


   numY--;// going down till we finish all the years
   i++;
  

}//end of while
    return listData;
    }//end method readData
    
    
}//end class
java linked-list computer-science
1个回答
0
投票

一般来说,当你得到一个错误,你应该包括被编译器标记为包含错误的行:) - 只是一个提示。

你的问题是,"静态 "是一个有点外来的概念,至少相对于学习java的前几周。我建议你避免使用它。通过使用这个作为骨架来做到这一点。

class MyApp {
    public static void main(String[] args) throws Exception {
        new MyApp().go();
    }

    void go() throws Exception {
        // your code goes here
    }
}

go 办法 String[] args param,如果你需要命令行参数。然后,不要做任何静态的东西,除了 main 这必须是。

static当然是有用的,但也许并不是一个特别值得你从java学习开始的概念,如果你不理解它,只会造成无尽的困惑。

如果你坚持不做这个改变,你就必须调用这个 readData 的方法。chainLadder,所以。new chainLadder().readData();,不 chainLadder.readData();.

拥有一个 "异源 "列表(一个包含不同概念的列表;你的列表既包含年值,也包含作为单独对象的成本)是很不像java的。

你应该做一个代表year-cost pair的类,并把它做成一个 List<YearInfo> 或什么的,或者更有可能的是你想要一张年限与成本的地图,所以,一 Map<Integer, Integer>.

你使用的是现有的链接列表 impl,而不是自己写。如果你因为作业需要而需要一个双链接列表,那么重点是让你自己写出整个实现,而不是使用 java.util.LinkedList 这样你就能学会如何使用链接列表。现实生活中没有任何一个要求是'它......必须......是一个双重链接的列表!'。鉴于与人类相关的只有几千年,你的列表永远不会包含足够的项目。因此。ArrayList 是正确的答案,即使它看起来在算法上不健全。也就是说,如果你想要一个列表--很有可能是 Map 是你要找的,如果这不是作业练习。

© www.soinside.com 2019 - 2024. All rights reserved.