【问题标题】:Multiple User Inputs with Try Catch InputMismatchException使用 Try Catch InputMismatchException 的多个用户输入
【发布时间】:2017-01-31 14:40:16
【问题描述】:

好的,所以我试图捕捉这些我可以做的用户输入,但问题是当我捕捉到它时,它不会返回到用户输入错误(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.");
        }
    }
}

【问题讨论】:

  • 你的try-catch在哪里?
  • 你的RefuseTruck班级在哪里?
  • @RajS.Rusia 这无关紧要。我只是想在测试类中捕获 inputmismatch 并在那里处理它。

标签: java try-catch


【解决方案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();

请记住,这会将“0”视为无效输入(再次执行循环)。

【讨论】:

  • 我已经更新了我的问题,因为它可能有点含糊,但那部分工作正常,但只是如果用户在第二次出错它会回到第一个输入,我'我不知道如何解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2018-01-16
相关资源
最近更新 更多