【问题标题】:Validate, inform if invalid, return to loop验证,如果无效则通知,返回循环
【发布时间】:2015-07-02 12:04:59
【问题描述】:

我的这部分代码有问题。该程序要求输入几个输入(姓名、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);

【问题讨论】:

  • 你能具体说明你的代码有什么问题吗?什么没有按预期工作?
  • 嗯,就目前而言,程序只是卡在一遍又一遍地询问成绩。我是否输入了无效(12)或有效(9-12)响应。
  • while (userGrade >= 9 || userGrade

标签: java validation input


【解决方案1】:

试试这样的:

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);

【讨论】:

  • 你没有处理用户写foo而不是数字的情况。
  • 是的,这只适用于整数值。如果您需要对可能的错误进行额外控制,请不要使用 nextInt() .... 使用 nextLine() 并解析它。
  • 这会显示无效消息并返回循环(再次询问),但即使响应在 9-12 之内,它仍然会再次询问。
  • 就是这样! Gah,我觉得我很近,但又很远。非常感谢!
【解决方案2】:

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

改变

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

到:

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

||接受任何大于等于 9 和小于等于 12 的值。这两个条件最终使得任何整数在条件下都为真。

【讨论】:

  • 实际上应该是while ( grade &lt; 9 || grade &gt; 12),因为循环应该继续直到给出一个有效的数字
【解决方案3】:

您可以将任务拆分为较小的任务。例如创建

的辅助方法
  • 将从 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);

【讨论】:

  • 感谢您的回复!我应该说我是 Java 的初学者。我的经验很少,但我通常可以接受一些事情。我只是想用一个简单的程序来解释它,看看我能走多远(复杂)。我喜欢您将某些任务分解为单独方法的建议!
  • 这些“帮助”方法将进入我的 main() 类,对吗?
  • 是的。但由于我也将它们设为公开和静态,您可以将它们放在您想要的任何类中,然后导入该类。这样您就可以像OtherClass.method(data) 一样使用它们。你也可以像import static some.package.with.OtherClass.ourStaticMethod那样使用静态导入,像ourStaticMethod(data)那样使用它。
猜你喜欢
  • 2014-11-20
  • 2016-11-13
  • 2012-05-09
  • 2018-12-03
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
  • 2015-08-03
  • 2019-01-15
相关资源
最近更新 更多