折叠数组值的索引

时间:2016-10-26 01:30:48

标签: java arrays

该程序需要十个用户输入整数,并将它们存储到一个数组中。它应该找到最大的值,并找到值的索引。目前,它找到了最大的价值。

但是,我不知道如何让它找到该值的索引。我觉得我可能会过度复杂化一个简单的解决方案。任何帮助或建议将不胜感激,谢谢!

public static void main(String[] args) {

    int[] numbers;
    numbers = new int[10];
    int largest = numbers[0];
    int counter;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Please enter 10 numbers: ");

    for (counter = 0; counter < numbers.length; counter++) {
        numbers[counter] = keyboard.nextInt();
    } 


    for (int i : numbers) {

        if (i > largest) {
            largest = i;

        } 
    } 
    System.out.print("The largest number is: " + largest);
    System.out.println(" ");
    System.out.print("That number is stored at index " +  );
    } 
 } 

2 个答案:

答案 0 :(得分:2)

同时跟踪最大及其位置

public static void main(String[] args) {

    int[] numbers;
    numbers = new int[10];
    int largest = numbers[0];
    int largest_i = 0;
    int counter;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Please enter 10 numbers: ");

    for (counter = 0; counter < numbers.length; counter++) {
        numbers[counter] = keyboard.nextInt();
        if (numbers[counter] >= largest) {
            largest = numbers[counter];
            largest_i = counter;
        }
    } 

    System.out.print("The largest number is: " + largest);
    System.out.println(" ");
    System.out.print("That number is stored at index " +  );
    } 
 } 

答案 1 :(得分:0)

你可以创建一个名为'largestIndex'的变量来存储索引值。

不使用foreach循环,而是使用for循环,它从0迭代到numbers.length,每次找到大于'maximum'的数字时,都会更新largestIndex变量。