Do-while循环异常

时间:2016-10-26 16:50:38

标签: java exception do-while

此代码旨在获取十个用户输入的整数,并查找最大值以及该最大值的索引。我需要为这个特定版本使用do while循环。

我可以输入十个数字,但是,尝试获取最大数字及其索引时会出现异常。我不完全确定如何解决这个问题。任何帮助或建议将不胜感激,谢谢!

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);

2 个答案:

答案 0 :(得分:3)

您可能正在获取索引超出范围的异常。这是因为你在循环外做了if检查。

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

但是,此时,计数器为10,而索引仅为0-9。

将if块移动到循环中以检查最大值。

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

答案 1 :(得分:-1)

以下是您找到最大数字的方法:

public static void main(String[] args) {
        final int[] numbers;
        numbers = new int[10];
        int largest = Integer.MIN_VALUE;//set largest to minimum value

        int counter = 0;
        int index = 0;

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

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


        do {
            numbers[counter] = keyboard.nextInt();//get the numbers here
            keyboard.nextLine();
            if(numbers[counter]>largest){//compare the entered number with the current largest number, if greater assign largest to the current number
                largest = numbers[counter];
                index = counter;//store the index of the largest number found 
            }
            counter++;//increment array counter
        } while (counter < numbers.length);

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

    }