【问题标题】:JAVA - Verifying if input is integers [duplicate]JAVA - 验证输入是否为整数
【发布时间】:2017-11-25 18:11:40
【问题描述】:

我正在尝试在 do-while 循环中插入一个 do-while 循环,以检查输入是否为整数。我在要插入 do-while 循环的地方添加了一条注释。除了那部分,一切都很好。

public static void main(String[] args){
    int num1, num2;
    char response;
    Scanner in = new Scanner(System.in);
    Scanner reader = new Scanner(System.in);

    do {    
        System.out.print("Enter number: ");
        num1 = in.nextInt();
        response = (char) reader.nextLine().charAt(0);

        //I want to check if the input is integer here
        do{
            System.out.println("Invalid input!\nPlease input integers only!");
        } while (response != /*something*/);

        for(num2=0; num2 < 11; num2++) {
            System.out.println(num1 + "X" + num2 + "=" + (num1 * num2));
            }

        do {
            System.out.println("\nDo you want to try again? [y/n]");
            response = (char) reader.nextLine().charAt(0);
            if (response != 'n'&& response != 'N' && response != 'Y' && response != 'y')
            System.out.println("Input invalid!");
        } while (response != 'n' && response != 'N' && response != 'y' && response != 'Y');

     } while (response != 'N' && response != 'n');{
         System.out.println("Thank you for using the table");}
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!请咨询stackoverflow.com/help/how-to-ask,特别关注相关信息(已由@StephenC编辑)。
  • 顺便说一句,您可以加粗预格式化代码。指向某一行的典型方法是在代码中添加注释以显示您在谈论的位置。
  • Integer.parseInt 在这里可能会有所帮助:)
  • 不要将多个Scanner 包裹在同一个源上(在您的情况下为System.in)。
  • 下次请做一点研究。这是一件超基本的事情;并且之前已经被无数新手询问过。并回答。又一次...

标签: java java.util.scanner


【解决方案1】:

您可以使用以下方式检查而不是使用 do while

try{
    yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
    //handle exception here
}

【讨论】:

    【解决方案2】:

    您可以使用“蛮力”并尝试解析用户输入,如果给出无效的内容,那么您会得到 NumberFormatException

        int num1 = 0;
        String intCandidate = null;
        boolean valid = false;
        Scanner in = new Scanner(System.in);
    
        while (!valid) {
            try {
                System.out.print("Enter number: ");
                intCandidate = in.nextLine();
                num1 = Integer.parseInt(intCandidate);
                valid = true;
            } catch (NumberFormatException e) {
                System.out.print("Nope... ");
            }
        }
        in.close();
        System.out.println("Thanks!");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多