Shibaku Shibaku - 1 month ago 22
Java Question

Do-while loop exception

This code is designed to get ten user-input integers, and find the max value as well as the index of that max value. I'm required to use a do while loop for this specific version.

I can enter the ten numbers, however, there is an exception when trying to get the largest number and its index. I'm not entirely sure how to go about fixing this. Any help or advice would be appreciated, thank you!

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

final Scanner keyboard = new Scanner(System.in);

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


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

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

Answer

You're probably getting an index out of bounds exception. This is because you do the if check outside the loop.

if (numbers[counter] >= largest)...

However, at this point, counter is 10, while the indexes only go from 0-9.

Move the if block into the loop to check for the max value.

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