I have a method that takes in an array (created by Scanner input in main) and sorts the array to find the most common words before printing the length of those words. However, I'm also trying to have an error message pop up if two different elements have the same length; this is where I'm having trouble getting started.
Method:
//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
Any suggestions?
CodePudding user response:
- String comparison -
arr[i] == arr[i-1]
does not work. Each string object is different for Java. Usearr[i].equals(arr[i-1])
. - When you check
count > maxCount
, it means there is definitely a string more frequent than the previous one. However, what ifcount == maxCount
? - It would mean you have found two strings with equal frequency.
Use a flag that tells you if there are multiple max frequency strings or not. So now we are going to check both for greater and equal conditions and based on what is true, we are going to set a flag 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