扫描数组以获得最常见字长的方法,但如果两个不同的元素具有相同的长度则发送错误消息

Method that scans array for most common word length, but sends error message if two different elements have the same length

我有一个方法接收一个数组(由 main 中的 Scanner 输入创建)并对数组进行排序以在打印这些单词的长度之前找到最常见的单词。但是,如果两个不同的元素具有相同的长度,我也试图弹出一条错误消息;这是我开始时遇到的问题。

方法:

//Return the length of the most common words
public static int lengthOfWord(String[] arr){
  
  int arrLength = arr.length;
  int count = 1; 
  int maxCount = 1;
  String temp = arr[0]; 
  
  //Sort through array
  for (int i = 1; i < arr.length; i++)  { 
     if (arr[i] == arr[i - 1]) {
        count++;
     } else {
     if (count > maxCount) { 
        maxCount = count; 
        temp = arr[i - 1];
     }//End of conditional
     count = 1;
     }//End of conditional
  }// End of for loop 

  //Declare most frequent length
  if (count > maxCount) { 
     maxCount = count; 
     temp = arr[arrLength - 1];
  }//End of conditional

  return temp.length();

}//End of lengthOfWord

有什么建议吗?

  1. 字符串比较 - arr[i] == arr[i-1] 不起作用。每个字符串对象对于 Java 都是不同的。使用 arr[i].equals(arr[i-1]).
  2. 当你勾选count > maxCount时,说明肯定有一个字符串比前一个更频繁。但是,如果 count == maxCount 呢? - 这意味着您找到了两个频率相同的字符串。

使用一个标志来告诉您是否有多个最大频率字符串。所以现在我们要检查更大和相等的条件,并根据什么是真的,我们将设置一个标志 unique.

//Return the length of the most common words
public static int lengthOfWord(String[] arr){
  
  int arrLength = arr.length;
  int count = 1; 
  int maxCount = 1;
  boolean unique = true;
  String temp = arr[0]; 
  
  //Sort through array
  for (int i = 1; i < arr.length; i++)  { 
     if (arr[i] == arr[i - 1]) {
        count++;
     } else {
     if (count > maxCount) { 
        unique = true;
        maxCount = count; 
        temp = arr[i - 1];
     } else if(count == maxCount) {
        unique = false;
     }
     //End of conditional
     count = 1;
     }//End of conditional
  }// End of for loop 

  //Declare most frequent length
  if (count > maxCount) { 
      unique = true;
      maxCount = count; 
      temp = arr[i - 1];
  } else if(count == maxCount) {
      unique = false;
  }//End of conditional

  if(!unique) {
    System.out.println("ERROR"); // or whatever you want to do in this condition 
  }


  return temp.length(): ;

}//End