Shibaku Shibaku - 1 month ago 10
Java Question

Fiding the index of an array value

This program takes ten user-input integers, and stores them into an array. It is supposed to find the largest value, and find the index of the value. Currently, it finds the largest value.

However, I'm not sure how to make it find the index of that value. I feel like I may be over-complicating a simple solution. Any help or advice would be appreciated, thank you!

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

Answer

Track largest and its position simultaneously

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