JAVA - 验证输入是否为整数

时间:2017-06-22 12:45:40

标签: java java.util.scanner

我试图在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");}
}

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以使用“暴力”并尝试解析用户输入,如果出现无效的内容,则会获得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!");