开发者

Custom Linklist class error

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: cannot find symbol symbol : method hasNext() location: class java.lang.String while (myArray.hasNext()) { ^ LinkedList.java:17: cannot find symbol symbol :开发者_如何学JAVA method next() location: class java.lang.String String word = myArray.next(); ^ 2 errors

Few Questions...

  1. Why did this error occur, i am trying to pass my Array of Strings. Still its not taking.
  2. Can't we not declare Array of Strings like in JavaScript way.

    String myArray[] = ["assa","asas"];

  3. What does the hasNext() and the next Method do?


Java arrays don't have next and hasNext methods on them. You are probably thinking of iterators, which are typically used with container classes/interfaces such as java.util.List.

Note that you can initialize String arrays thus:

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


Here is a much more succinct way to iterate through the array

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

}

That will iterate through the array, assigning the current value to word at each pass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜