验证int值

时间:2016-11-01 21:43:32

标签: java validation

我正在尝试打印一条消息“错误”,然后每次用户输入非int的内容时再输入一次值。

我有以下代码:

do {

    System.out.println("Enter last name: ");
    lastName = input.next();

    System.out.println("Enter first name: ");
    firstName = input.next();

    do {
        System.out.println("Enter exam 1 score: ");
        if (input.hasNextInt()) {
            ex1 = input.nextInt();

            System.out.println("Enter exam 2 score: ");
            ex2 = input.nextInt();

            System.out.println("Enter exam 3 score: ");
            ex3 = input.nextInt();

            valid = true;

        } else {
            System.out.println("Incorrect choice. Write the score in numbers." + "\n");
            valid = false;
            input.next(); // Prevents infinite loop
        }
    } while (!valid);

只有当用户在考试1中出错时才能正常工作,但如果他们在考试2或3考试时出错,则会给我一个错误。

我将非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

尽量不要一次又一次地编写相同的代码。使用循环。

final int MAX_SCORES = 3;

while (true) {
    System.out.println("Enter last name: ");
    String lastName = input.next();

    System.out.println("Enter first name: ");
    String firstName = input.next();

    int scores = new int[MAX_SCORES];
    for (int i = 0; i < MAX_SCORES; ) {
        System.out.printf("Enter exam %d score: ", i + 1);
        if (input.hasNextInt()) { 
            scores[i++] = input.nextInt(); // increment 'i' after assignment
        } else {
             System.out.println("Incorrect choice. Write the score in numbers.\n");
             // Loop will repeat at same value of 'i'
        }
    }  

    System.out.println("Again? (Y/N)");
    if (input.next().equalsIgnoreCase("n")) break; // Prevents infinite loop
}

答案 1 :(得分:0)

您只对输入用户1进行了检查。您需要为每个用户分别执行if语句。

    if (input.hasNextInt()) {
        ex1 = input.nextInt();
    } else {
        System.out.println("Incorrect choice. Write the score in numbers." + "\n");
        valid = false;
        input.next(); // Prevents infinite loop
    }
        System.out.println("Enter exam 2 score: ");
    if (input.hasNextInt()) {
        ex2 = input.nextInt();
    } else {
        System.out.println("Incorrect choice. Write the score in numbers." + "\n");
        valid = false;
        input.next(); // Prevents infinite loop
    }
        System.out.println("Enter exam 3 score: ");
    if (input.hasNextInt()) {
        ex3 = input.nextInt();

        valid = true;

    } else {
        System.out.println("Incorrect choice. Write the score in numbers." + "\n");
        valid = false;
        input.next(); // Prevents infinite loop
    }

else代码包装在方法或其他内容中会更好,但这就是主意。