Reputation: 15044
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 : method next() location: class java.lang.String String word = myArray.next(); ^ 2 errors
Few Questions...
Can't we not declare Array of Strings like in JavaScript way.
String myArray[] = ["assa","asas"];
What does the hasNext() and the next Method do?
Upvotes: 0
Views: 74
Reputation: 1756
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.
Upvotes: 1
Reputation: 272647
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" };
Upvotes: 3