如何比较java中字符串数组中的元素?

我试图在字符串数组中找到重复的单词。

这是我的比较代码:

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

在if语句中,它表示NullPointerException 。 这是什么意思? 有一个更好的方法吗? 我试着干脆做

 if (stringArray[i] == stringArray[j] && i!=j) 

但这一直给我错误的答案。

你可以这样做以获得更好的表现:

 public int getDuplicateCount(Integer[] arr){ int count = 0; Set set = new HashSet(); for (int i = 0; i < arr.length; i++) { if (set.contains(arr[i])) count++; set.add(arr[i]); } return count; } 

NullPointerException意味着未设置其中一个数组成员(即它为null)

不要使用==来比较字符串。

你是在正确的轨道上 – 很可能是stringArray[]包含一些未设置的成员。 Eacy修复是在使用值之前进行空检查。

 for ( int j = 0 ; j < wordCount ; j++) { for (int i = wordCount-1 ; i > j ; i--) { String wordi = stringArray[i]; String wordj = strinArray[j]; // If both are null it won't count as a duplicate. // (No real need to check wordj - I do it out of habit) if (wordi != null && wordj != null && wordi.compareTo(wordj) == 0 && i!=j) { //duplicate duplicates++; } } } wordCount -= duplicates; System.out.print("\nNumber of words, not including duplicates: " + wordCount); 

这意味着stringArray[i]null ,即你的数组在某处有一个null条目。 您可能在其他地方出现逻辑错误,并且未正确设置arrays的某些元素。

如果您的数组合法地包含空值,则必须在尝试调用stringArray[i]上的方法之前显式检查:

 if (stringArray[i] == null){ // Do whatever } else if (stringArray[i].compareTo(stringArray[j]) == 0 && i!=j) { //duplicate duplicates++; } 

空指针可能是因为您的数组中有任何空值。

您的代码无法正常工作,因为您需要在需要查找重复项的同一arrays上进行操作

您可以使用以下代码来计算数组中的重复单词。

 public class WordCount { public static void main(String args[]){ String stringArray[]={"a","b","c","a","d","b","e","f"}; Set mySet = new HashSet(Arrays.asList(stringArray)); System.out.println("Number of duplicate words: "+ (stringArray.length -mySet.size())); System.out.println("Number of words, not including duplicates: "+ mySet.size()); } } 

在这里,我看到你正试图找到给定字符串的唯一元素数。 我建议使用HashSet来获得更好的解决方案。

 public int getUniqueElements(String str) { HashSet hSet = new HashSet<>(); // iterate given string, hSet only adds unique elements to hashset for(int i = 0; i < str.length() ; i++ hSet.add(str.charAt(i)); return hSet.size(); }