Java数组:在数组中找到存储值的索引。是

时间:2017-09-25 13:01:14

标签: java arrays

我需要创建一个程序,让用户输入存储在数组中的10个数字。我已经有了代码,用于确定用户输入的最小和最大数字,我遇到的问题是如何显示最大值和最小值所在的索引。

以下是我的代码:

import java.util.Scanner;

public class Array {

    static Scanner in = new Scanner(System.in);

    public static void main(String[] args) {

        int numbers[] = new int[10];
        int smallest = Integer.MAX_VALUE, largest = numbers[0];

        for(int i = 0; i < 10; i++){ 
//I get the "Can't find symbol error" on this part: index = i;

            index = i;
            System.out.print("Array Number " + i + ": ");
            numbers[i] = in.nextInt();
        }
        for (int n = 0 ; n < numbers.length; n++) {
            if (numbers[n] < smallest) {
                smallest = numbers[n];
            } 
            if (numbers[n] > largest) {
                largest = numbers[n];
            }      

        }

//And this part, which it the: index

        System.out.println("Maximum number is " + largest + " located in index " + index);
        System.out.println("Minimum number is " + smallest + " located in index " + index);

    }   

}

我想知道哪个部分我弄错了。

1 个答案:

答案 0 :(得分:0)

index未定义,因此您会收到错误。

int index = i;

要查找最小和最大数字的索引,只要找到更小或更大的值,就需要更新两个索引。您甚至不需要保存smallestlargest,因为它们无论如何都存储在数组中,并且可以使用这两个索引进行检索(感谢Andrew S.提及):

int maxIndex = -1, minIndex = -1;

for (int n = 0 ; n < numbers.length; n++) {
    if (numbers[n] < smallest) {
        smallest = numbers[n];
        minIndex = n;
    } 
    if (numbers[n] > largest) {
        largest = numbers[n];
        maxIndex = n;
    }      
}

System.out.println("Maximum number is " + numbers[maxIndex]+ " located in index " + maxIndex);
System.out.println("Minimum number is " + numbers[minIndex] + " located in index " + minIndex);