自定义链接列表类错误

时间:2011-09-04 23:41:53

标签: java

class Link {
    public Link next;    
    public String data; 
}

public class LinkedList {
    public static void main(String[] args) {
        String myArray[] = new String[2];
        myArray[0] = "John";
    myArray[1] = "Cooper";

        Link first = null;    
        Link last  = null;    

        while (myArray.hasNext()) {
            String word = myArray.next();

            Link e = new Link();    
            e.data = word;          

            //... Two cases must be handled differently
            if (first == null) {
                first = e;            
            } else {
                //... When we already have elements, we need to link to it.
                last.next = e;       
            }
            last = e;                
        }

        System.out.println("*** Print words in order of entry");
        for (Link e = first; e != null; e = e.next) {
            System.out.println(e.data);
        }

    }
}
  

LinkedList.java:16:找不到符号符号:方法hasNext()   location:类java.lang.String           while(myArray.hasNext()){                            ^ LinkedList.java:17:找不到符号   symbol:方法next()位置:类java.lang.String               String word = myArray.next();                                       ^ 2错误

几个问题......

  1. 为什么会出现此错误,我正在尝试传递我的数组字符串。仍然没有采取。
  2. 我们不能像JavaScript那样声明字符串数组。

    String myArray [] = [“assa”,“asas”];

  3. hasNext()和下一个方法有什么作用?

2 个答案:

答案 0 :(得分:3)

Java数组上没有nexthasNext方法。您可能正在考虑迭代器,它通常用于容器类/接口,例如java.util.List

请注意,您可以初始化String数组:

String[] myArray = { "foo", "bar" };

答案 1 :(得分:1)

这是一种更简洁的迭代数组的方法

for(String word : myArray) {
//Keep the rest of the code the same(removing the String word = myArray.next(); line

}

这将迭代数组,在每次传递时将当前值分配给单词。