繁体   English   中英

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

[英]how to compare elements in a string array in java?

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

这是我的比较代码:

   for ( int j = 0 ; j < wordCount ; j++)
   {    
       for (int i = wordCount-1 ; i > 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<Integer> set = new HashSet<Integer>();
     for (int i = 0; i < arr.length; i++) {
         if (set.contains(arr[i]))
             count++;
         set.add(arr[i]);
      }
      return count;
 }

NullPointerException表示未设置您的数组成员之一(即为null)

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

您处在正确的轨道上stringArray[]包含一些未设置的成员。 有效的解决方案是在使用值之前先进行空检查。

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条目。 您可能在其他地方遇到逻辑错误,并且数组的某些元素未正确设置。

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

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

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

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

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

public class WordCount {


public static void main(String args[]){
    String stringArray[]={"a","b","c","a","d","b","e","f"};

    Set<String> mySet = new HashSet<String>(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<Character> 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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM