在java中输入验证循环

时间:2014-11-06 07:35:39

标签: loops

我如何编写输入验证循环和至少一个其他循环,无论是反控制还是哨兵控制。你能帮我写一下如何编写任何类型的代码吗?

1 个答案:

答案 0 :(得分:0)

final int SIZE = 10;
    int [] array = new int[SIZE];
    Scanner input = new Scanner(System.in);

    for(int i=0; i < array.length; i++)
    {
        try 
        {
            do
            {
                System.out.print("Enter Number " + (i+1) + ": ");
                array[i] = input.nextInt();

                if(array[i] < 0)
                    System.out.println("Invalid Input - Must be Greater than 0");

            }while(array[i] < 0);

        }
        catch (InputMismatchException e)
        {
            System.out.println("Invalid Input - Not an Int - Re-Enter");

            input.nextLine();
            i--;
        }
    }