【发布时间】:2019-05-23 12:29:43
【问题描述】:
我是编码的初学者。目前我正在学习数组。
在下面的代码中,我尝试使用String 数组显示用户输入的单词。使用增强的 for 循环时,代码显示 null。谁能解释一下这个问题?
代码在正常的 for 循环中运行良好。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word;
int count = 0;
String[] words = new String[100];
System.out.println("Enter the words (enter 'done' when finished):");
do {
System.out.println("Enter word "+ (count+1));
word=scanner.nextLine();
if (!word.equalsIgnoreCase("done")) {
words[count]=word;
count++;
}
}while (!word.equalsIgnoreCase("done"));
System.out.println("Words entered are:");
for (String print:words){
System.out.println(print);
}
scanner.close();
}
代码应显示用户输入的单词,但显示的是null 而不是单词。
【问题讨论】:
-
作为初学者,我假设您还没有了解
ArrayList。当你学习它时,你会发现ArrayList在这种情况下比数组更适合。当您不确切知道需要多少元素时使用它。 -
@DodgyCodeException 是的,然后还有链表。此时选择正确的列表非常令人困惑。
-
这是一个基于性能的决定。在大多数情况下,ArrayList 会更快。不要太担心它。现在只需使用 ArrayList。如果您在某个时候开始编写对性能至关重要的应用程序,那么您可能会知道如何衡量性能以确定哪个是最好的。