我不太确定问题出在哪里。 代码工作正常,但是,在我输入几个单词后,即:
猫
猫
结束
它告诉我:
猫
猫
空。
我的猜测是字符串 k 或数组的大小。 所以我想,我需要以某种方式输入“结束”工作,对吗?
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
String type;
String word;
String words[] = new String[100];
int i = 1;
String k = "end";
System.out.println("Type a word: ");
word = sc.next();
while (word.compareToIgnoreCase(k) != 0) {
words[i] = word;
i = i + 1;
word = sc.next();
}
System.out.println("What type A,B,C:");
typ = sc.next();
if (typ.equals("B")) {
int lenght = words.length;
lenght = i + 1;
i = 1;
while (i < lenght) {
System.out.print(words[i]);
System.out.println();
i = i + 1;
}
}
}
}
最佳答案
您只需将最后一个单词添加到数组中即可:
while (word.compareToIgnoreCase(k) != 0) {
words[i] = word;
i = i + 1;
word = sc.next();
}
words[i] = word; // Add the last item entered
顺便说一下,我建议使用 List<String>
而不是String[]
,并调用 words.add(word)
。一方面,这意味着您不必跟踪索引 ( i
)。更重要的是,列表可以变得任意长,并且您将只使用所需的内存。
关于java - 摆脱数组中的 null。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309461/