gpt4 book ai didi

java - 为什么我的字符串数组有空值? (java)

转载 作者:行者123 更新时间:2023-12-01 17:28:49 25 4
gpt4 key购买 nike

Possible Duplicate:
how to compare elements in a string array in java?

我试图将数组中的单词设置为字符串,然后计算不包括重复项的单词数,但是当我尝试使用 if 语句检查重复项时,它显示“NullPointerException”,这意味着存在一个数组中为空。为什么数组有空值?

下面是设置字符串数组的代码,输入为“DO UNTO OTHERS AS YOU WOULD HAVE THEM DO UNTO YOU”:

   String[] stringArray = new String[wordCount];
while (!line.equals("DONE"))
{
for ( int k = 0 ; k < wordCount ; k++)
{
//put tokens into string array
StringTokenizer tokens = new StringTokenizer(line);
stringArray[k] = tokens.nextToken();
}
}

以下是导致 NullPointerException 的比较和 if 语句的代码:

   for ( int j = 0 ; j < wordCount ; j++)
{
for (int i = j+1 ; i < wordCount ; i++)
{
if (stringArray[i] == null)
{
stringArray[i] = "null";
}
else if (stringArray[i].compareTo(stringArray[j]) == 0 && i!=j)
{
//duplicate
System.out.print("\n" + stringArray[j]);
duplicates++;
}
}
}
wordCount -= duplicates;
System.out.print("\nNumber of words, not including duplicates: " + wordCount);

我正在尝试进行 null 检查,但结果仍然很差,因为它会增加更多重复项,因为当我将 stringArray[i] 更改为“null”时,它也会更改 stringArray[j]

请帮忙!我长期以来一直在尝试解决这个问题

最佳答案

您应该使用equals()而不是compareTo()。如果传递 null,则 compareTo() 引发 NullPointerException

Comparable 的 Java 文档

Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

          if (stringArray[i] == null) {
continue;
} else if (stringArray[i].equals(stringArray[j]) && i != j) {
// duplicate
duplicates++;
}

完整的源代码应该是这样的。 我没有更改 for 循环内的任何逻辑。

    String line = "DO UNTO OTHERS AS YOU WOULD HAVE THEM DO UNTO YOU";
String[] stringArray = line.split("\\s");//Use split StringTokenizer use is discouraged in new code
int duplicates = 0;
int wordCount = stringArray.length;
for (int j = 0; j < stringArray.length; j++) {
for (int i = j + 1; i < stringArray.length; i++) {
if (stringArray[i] == null) {
stringArray[i] = "null";
} else if (stringArray[i].equals(stringArray[j]) && i != j) {
// duplicate
System.out.print("\n" + stringArray[j]);
duplicates++;
}
}
}
wordCount -= duplicates;
System.out.print("\nNumber of words, not including duplicates: "
+ wordCount);

关于java - 为什么我的字符串数组有空值? (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12947552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com