验证,通知无效,返回循环

时间:2015-07-02 12:05:00

标签: java validation input

我的代码的这一部分出了问题。该程序要求输入几个(名称,ID,等级等),然后将结果打印出来。

我决定脱离教程,现在已经在一个众所周知的墙上砸了我的脑袋 -

我想要的伪代码:

Ask user for grade between 9 and 12
If input is less than 9 or greater than 12, return failed message and -return to loop-
If input acceptable, continue to next question. 

目前的代码如下:

do {
    System.out.print("Grade (9-12): ");
    while (!keyboard.hasNextInt()) {
        System.out.printf("message saying you're wrong");
        keyboard.next();
    }
    userGrade = keyboard.nextInt();
} while (userGrade >= 9 || userGrade <= 12);

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

boolean correct = true;
do {
    System.out.print("Grade (9-12): ");
    userGrade = keyboard.nextInt();
    if (userGrade < 9 || userGrade > 12) {
        correct = false;
        System.out.println("message saying you're wrong");
    } else {
        correct = true;
    }
} while (!correct);

答案 1 :(得分:0)

我认为问题出在逻辑上......

更改

 while (userGrade >= 9 || userGrade <= 12);

为:

while (userGrade >= 9 && userGrade <= 12);

||接受任何更高且等于9且低于等于12的值。这两个条件最终使得任何整数在该条件下都为真。

答案 2 :(得分:0)

您可以将您的任务拆分为较小的任务。例如,创建辅助方法

  • 将从Scanner读取,直到找到整数,然后返回

    public static int getInt(Scanner scanner, String errorMessage){
        while (!scanner.hasNextInt()) {
            System.out.println(errorMessage);
            scanner.nextLine();
        }
        return scanner.nextInt();
    }
    
  • 或将检查数字是否在范围内(但这只是为了便于阅读)

    public static boolean isInRange(int x, int start, int end){
        return start <= x && x <= end;
    }
    

因此,使用此方法,您的代码可能看起来像

Scanner scanner = new Scanner(System.in);
int x;

System.out.println("Please enter a number in range 9-12:");
do {
    x = getInt(scanner, "I said number. Please try again: ");
    if (!isInRange(x, 9, 12))
        System.out.println("I said number in range 9-12. Please try again: ");
} while (!isInRange(x, 9, 12));

System.out.println("your number is: " + x);