使用Try Catch InputMismatchException

时间:2017-01-31 14:40:17

标签: java try-catch

好的,所以我试图捕捉这些用户输入,我可以做但问题是当我抓住它时,它不会返回用户错误输入(InputMismatchException)的输入,但它会返回到循环的开始。让我们说如果用户在第二个输入上出错,它将返回到用户正确输入的第一个输入。我只是将它保持基本状态并取消了我的尝试。

    public class TestRefuseTruck {

    public static void main(String[] args) {
        int maxBins;
        int rate;
        int weight;
        int count = 0;
        Scanner in = new Scanner(System.in);
        try {
            System.out.println("Enter the number of bins the truck can collect: ");
            maxBins = in.nextInt();
            System.out.println("Enter the cost per kilo:");
            rate = in.nextInt();
            RefuseTruck r = new RefuseTruck(maxBins, rate);
            while (count < maxBins) {
                System.out.println("Enter the weight for bin " + (count + 1));
                weight = in.nextInt();
                if (r.collectBin(weight) == true) {
                    count++;
                }
            }
            r.printStats();
        } catch (InputMismatchException e) {
            System.out.println("Incorrect Input.");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

更新

将每个输入保持在单独的while循环中,直到输入正确为止:

int maxBins = 0;
int rate = 0;
int weight = 0;
int count = 0;
Scanner in = new Scanner(System.in);
while(maxBins == 0){
    try {
        System.out.println("Enter the number of bins the truck can collect: ");
        maxBins = in.nextInt();
    } catch (InputMismatchException e) {
        System.out.println("Incorrect Input.");
    }
}
while(rate == 0){
    try {
        System.out.println("Enter the cost per kilo:");
        rate = in.nextInt();
    } catch (InputMismatchException e) {
        System.out.println("Incorrect Input.");
    }
}
RefuseTruck r = new RefuseTruck(maxBins, rate);
while (count < maxBins) {
    try {
        System.out.println("Enter the weight for bin " + (count + 1));
        weight = in.nextInt();
    } catch (InputMismatchException e) {
        System.out.println("Incorrect Input.");
        continue;
    }
    if (r.collectBin(weight) == true) {
        count++;
    }
}
r.printStats();

请记住这个问题&#34; 0&#34;作为无效输入(再次执行循环)。