[英]Array index printing wrong value
我有以下Java代碼。
import java.util.Arrays;
public class Cook {
public static void main(String[] args) {
int num[] = { 3, 1, 5, 2, 4 };
getMaxValue(num);
}
public static void getMaxValue(int[] num) {
int maxValue = num[0];
int getMaxIndex = 0;
for (int i = 1; i < num.length; i++) {
if (num[i] > maxValue) {
maxValue = num[i];
}
}
getMaxIndex = Arrays.asList(num).indexOf(maxValue);
System.out.println(getMaxIndex + " and " +maxValue);
}
}
在上面的代碼中,我試圖檢索數組中的最大值以及它的索引,但這里我得到的輸出是
-1 and 5
最大值返回正常,但不確定索引有什么問題。 這實際上應該打印2
,但它打印-1
,請讓我知道我哪里出錯了,我該如何解決這個問題。
Thankd
您應該更新循環中的最大索引:
int maxValue = num[0];
int getMaxIndex = 0;
for (int i = 1; i < num.length; i++) {
if (num[i] > maxValue) {
maxValue = num[i];
getMaxIndex = i;
}
}
Arrays.asList(num).indexOf(maxValue);
返回-1
是一個基元數組由Arrays.asList
轉換為單個元素的List
(數組本身),並且該List
不包含maxValue
(它只包含原始數組)。
需要在迭代時更新索引, getMaxIndex = i;
public static void getMaxValue(int[] num) {
int maxValue = num[0];
int getMaxIndex = 0;
for (int i = 1; i < num.length; i++) {
if (num[i] > maxValue) {
maxValue = num[i];
getMaxIndex = i;
}
}
System.out.println(getMaxIndex + " and " + maxValue);
}
產量
2 and 5
以下是@Eran所指的內容。
它被轉換為size 1
List
,包含一個元素(數組本身)。
按照Javadoc, indexOf
返回此列表中第一次出現的指定元素的索引,如果此列表不包含該元素,則返回-1。
因此它inside List
搜索maxValue
而not inside array stored in 0th index of List
。
每個人都給出了很好的提示,但沒有人詳細解釋為什么它不起作用。
Arrays.asList()
使用簽名public static <T> List<T> asList(T... a)
,它接受可變數量的對象或僅占用對象數組。
但是, int
是基本類型而不是對象類型。 因此Arrays.asList(num)
不會被解釋為“取這個數組”,而是“將此對象作為一個對象”。 結果是List<int[]>
,其中找不到給定的數字(當然)。
因此,最好在搜索最大值時保持索引,正如其他答案已經建議的那樣。
以上答案是正確的,但你也可以這樣做
import java.util.Arrays;
public class Cook {
public static void main(String[] args) {
Integer num[] = { 3, 1, 5, 2, 4 };
getMaxValue(num);
}
public static void getMaxValue(Integer[] num) {
int maxValue = Arrays.asList(num).get(0);
int getMaxIndex = 0;
for (int i = 1; i < num.length; i++) {
if (Arrays.asList(num).get(i) > maxValue) {
maxValue = Arrays.asList(num).get(i);
}
}
getMaxIndex = Arrays.asList(num).indexOf(maxValue);
System.out.println(getMaxIndex + " and " +maxValue);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.