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错误
几个问题......
我们不能像JavaScript那样声明字符串数组。
String myArray [] = [“assa”,“asas”];
hasNext()和下一个方法有什么作用?
答案 0 :(得分:3)
Java数组上没有next
和hasNext
方法。您可能正在考虑迭代器,它通常用于容器类/接口,例如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
}
这将迭代数组,在每次传递时将当前值分配给单词。