0

我正在尝试从用户输入两个整数来生成一个数组。第一个数字确定数组中有多少元素,第二个数字将是随机值生成器的最大值。然后我将添加所有位置并找到最小值/最大值和平均值。现在,我正试图超越职责要求并处理异常并进行数据验证(此任务不需要)。

我无法捕捉错误并尝试从用户那里重新读取整数。现在它工作得很好,直到我第二次输入一个单词(在它在第一个块中引发异常之后。如果我输入另一个单词,它会移动到下一位代码(最大值输入)。

我想知道是否还有其他更好的方法可以做到这一点,或者我是否遗漏了什么。

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

public class main {

 public static void main(String[] args) {
    boolean dataValid = false;

    Scanner scan = new Scanner(System.in);

        System.out.println("Please enter the number of positions:");

        try     {

            do  {   
                int arrayPositions = scan.nextInt();

                if(arrayPositions < 1)  {
                    System.out.println("You cannot enter a negative number");
                    dataValid = false;
                } else if(arrayPositions > 100) {
                    System.out.println("Please use a number less than 101");
                    dataValid = false;
                } else {
                    dataValid = true;
                }

            } while (dataValid = false);

        } catch (InputMismatchException e)  {
            System.out.println("Please enter a whole integer!");
            System.out.println(scan.next() +" is not a valid input!");
            scan.next();
        }

    dataValid = false;

    do  {

        System.out.println("Please enter the maximum value:");
        int maxValue = scan.nextInt();

        if(maxValue < 1)    {
            System.out.println("Please enter a number greater than 0:");                
            dataValid = false;
        } else if (maxValue > 1000) {
            System.out.println("Please enter a number smaller than or equal to 1000:");
            dataValid = false;
        } else {
            dataValid = true;
        }

    } while(dataValid = false);
    }
}
4

0 回答 0