【问题标题】:Validating multiples input [duplicate]验证倍数输入
【发布时间】:2016-06-20 05:59:30
【问题描述】:

我不希望用户输入负值。如何检测负值以及InputMismatchException?这是我到目前为止的代码!该代码似乎无法正常工作,无法弄清楚问题出在哪里。我想验证用户输入以确保负数、字符串和双精度数无效,并提示用户输入正确的数字,该数字应为正整数。

            do {
                try {
                    System.out.println("How many " + teaName + " did you today?");
                    if(input.hasNextInt() && (numberItem = input.nextInt()) > 0) {
                        istrue = false;

                        numberItem = input.nextInt();

                    }

                } catch (InputMismatchException e) {
                    input.nextLine();
                    System.out.println("Please enter right number");
                    istrue = true;
                }
                catch (NoSuchElementException e){
                    System.out.println(" Please enter positive integers");
                }
            } while (istrue);

【问题讨论】:

  • 负数不是Scanner 抛出的异常,所以不能将它添加到catch 块中
  • 你能发布你的整个代码吗?

标签: java


【解决方案1】:
         do {
            try {
                System.out.println("How many " + teaName + " did you today?");
                if(input.hasNextInt()) {
                    if (numberItem = input.nextInt()) > 0) {
                        istrue = false;

                        numberItem = input.nextInt();
                    } else {
                        throw new InputMisMatchException("negative num");
                    }

                }

            } catch (InputMismatchException e) {
                input.nextLine();
                System.out.println("Please enter right number");
                istrue = true;
            }
            catch (NoSuchElementException e){
                System.out.println(" Please enter positive integers");
            }
        }while (istrue);

这应该可行,我所做的只是在数字为负数时抛出 InputMismatchException。

【讨论】:

  • 将 if 语句用于 continue do while 循环实际上比抛出异常并捕获它要快
  • 另外,异常不应该用于日常流程控制
猜你喜欢
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 2017-11-13
  • 2012-11-02
  • 2012-10-28
  • 2014-09-20
相关资源
最近更新 更多