2015-12-08 80 views
5

我有下面的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

+2

你真的需要数组... indexOf在这段代码中吗? –

+0

如果你花时间做一点调试,并检查你使用的2(!)函数中的每一个函数都做了什么,你就会知道。 – njzk2

回答

21

应当更新在循环中的最大指数:

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(它只包含原始数组)。

6

需求,同时迭代更新索引,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 1List,包含一个单一的元素(数组本身)。

作为每Javadoc中,indexOf

返回指定元件的第一次出现的索引在此 列表,或者-1,如果该列表中不包含的元素。

所以它搜索maxValueinside Listnot inside array stored in 0th index of List

enter image description here

1

以上的答案是正确的,但你也可以做

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); 
    } 
} 
+0

为什么所有这些转换使用'Arrays.asList'?如果你使用的是Integer [],你可以这样做:'List l = Arrays.asList(num); int max = Collections.max(l); int indexMax = l.indexOf(max);'。 3行... –

4

每个人都提供了很好的提示,但是在细节上没有人可以解释为什么它不工作。

Arrays.asList()由签名public static <T> List<T> asList(T... a)定义,该签名采用可变数量的对象或只是一个对象数组。

但是,int是原始类型而不是对象类型。因此Arrays.asList(num)不被解释为“接受此数组”,而是“将此对象作为一个对象”。结果因此是List<int[]>,其中给定的数字(当然)不能被找到。

因此,在搜索最大值时保持索引更好,因为其他答案已经提示。