[英]How do I make a method where I check certain values in an array rather than the whole array?
我創建了檢查整個數組並按字母順序檢索最新字符串的方法。 我現在要做的是更改該方法,以便用戶在數組中輸入 2 個位置,並讓該方法返回這 2 個位置之間的最新值。例如,如果我有一個 arrays 字符串, {"Bob", "Michael", "Joe", "Gazza", "Paul", "Barry"}
,我調用方法getMaxsValue(array,0,1)
。 它應該 output 的名字"Michael"
。
這是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;
}
而不是 for-each 循環,您應該只在給定索引之間循環。
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;
}
正如 GameDroids 指出的那樣,在 function 的開頭添加對給定位置的驗證可能是個好主意,即
if(pos1 > pos2 || pos1 < 0 || pos2 >= array.length){
//throw some exception
}
如果您只想比較兩個給定索引的值,就像這樣
public static String getMaxsValue(String[] array, int pos1, int pos2) {
if (array[pos1].compareTo(array[pos2]) > 0) {
return array[pos1];
}
return array[pos2];
}
對於 stream 愛好者來說,這里是另一種選擇
public static String getMaxsValue(String[] array, int pos1, int pos2) {
return Arrays.stream(array,pos1,pos2 +1).max(String::compareTo).orElse(null);
}
@GameDroids 對索引注釋的檢查也適用於此處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.