import java.util.InputMismatchException;
import java.util.Scanner;

public class array
{
    public static void main(String[] args)
    {
        int marks=0;
        Scanner input = new Scanner(System.in);
        int array[] = new int[5];
        System.out.println("Please enter the marks of students one by one");
        for(int i = 0;i < array.length;i++)
        {
            try
            {
                marks = input.nextInt();

            }
            catch(InputMismatchException e)
            {
                System.out.println(e);
                System.out.println("Please enter an integer value");
            }
            array[i]=marks;

        }
        System.out.println("index     Value" );
        for(int i=0;i<array.length;i++)
        {
            System.out.println("    "+i+"        "+array[i]);
        }
    }
}


以上是我的代码。
我试图捕获用户键入除整数值以外的任何其他数据的异常,并且它在捕获异常时工作正常。
但是问题在于它没有将控制权交还给用户。您将通过输出更好地理解它。
以下是我在执行时收到的消息。
它是从命令提示符复制的文本。

Please enter the marks of students one by one
abc
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
java.util.InputMismatchException
Please enter an integer value
index     Value
    0        0
    1        0
    2        0
    3        0
    4        0


如您所见,当我输入'abc'作为输入时,它捕获了异常并发出了正确的消息,但是它执行了5次,即我数组的大小。

为什么不将控制权还给用户?

最佳答案

问题在于,当发生异常时,您仍会计算该尝试,然后存储该值。您需要执行以下操作:

for(int i = 0;i < array.length;i++) {

  boolean validInput = false;
  do {
     try {
        marks = input.nextInt();
        array[i]=marks;
        validInput = true;
     } catch (InputMismatchException e) {
        System.out.println("Please enter an integer value");
     }
  } while (!validInput);

}


在此代码中,用户必须输入正确的值才能继续(内部while循环)

09-30 13:41
查看更多