I have created method which checks an entire array and retrieves the string which comes latest alphabetically. What I am trying to do now is to change that method so that the user enters 2 positions in the array and for the method to return the value that comes latest between the 2. eg if I have a string of arrays which say, {"Bob", "Michael", "Joe", "Gazza", "Paul", "Barry"}
, and I call the method getMaxsValue(array,0,1)
. it should output the name "Michael"
.
Here is the method getMaxsValue:
public static String getMaxsValue(String[] array, int pos1, int pos2) {
String longstr = array[0];
for (String s : array) {
if (s.compareTo(longstr) > 0) {
longstr = s;
}
}
return longstr;
}
Instead of a for-each loop you should only loop between the given indices.
public static String getMaxsValue(String[] array, int pos1, int pos2) {
String longstr = array[pos1];
for (int i = pos1; i <= pos2; i++) {
if (array[i].compareTo(longstr) > 0) {
longstr = array[i];
}
}
return longstr;
}
As GameDroids pointed out it might be a good idea to add a validation of the given positions at the beginning of your function ie
if(pos1 > pos2 || pos1 < 0 || pos2 >= array.length){
//throw some exception
}
If you only want to compare the values at the two given indices that would be something like this
public static String getMaxsValue(String[] array, int pos1, int pos2) {
if (array[pos1].compareTo(array[pos2]) > 0) {
return array[pos1];
}
return array[pos2];
}
For the stream enthusiasts here is an alternative
public static String getMaxsValue(String[] array, int pos1, int pos2) {
return Arrays.stream(array,pos1,pos2 +1).max(String::compareTo).orElse(null);
}
The check for the indices comment from @GameDroids applys here as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.