【问题标题】:Validating Scanner input in Java [closed]在 Java 中验证扫描仪输入 [关闭]
【发布时间】:2013-10-23 22:23:41
【问题描述】:

当输入非数字值时,如何阻止我的程序崩溃?我知道 kbd.hasNextLong,但我不确定如何实现它。

【问题讨论】:

标签: java validation input


【解决方案1】:

这是您可以验证它的方式:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean end = false;
    long value;
    while (end == false) {
        try {
            value = input.nextLong();
            end = true;
        } catch (InputMismatchException e) {
            System.out.println("Please input the right LONG value!");
            input.nextLine();
        }
    }
}

注意 input.nextLine() 在 catch 语句中。如果您输入一些非整数文本,它会跳转到 catch(导致在 nextInt 中无法读取整数),它会打印行消息,然后再次执行。但是输入的值并没有消失,所以即使你什么都不做,它也会再次崩溃。

input.nextLine()“刷新”你输入的内容。

使用 hasNextLong 是另一种方式(但是我更喜欢抛出异常,因为它是异常):

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean end = false;
    long value;

    while (end == false)  {
        if (input.hasNextLong()) {
            value = input.nextLong();
            end = true;
        } else {
            System.out.println("input the LONG value!");
            input.nextLine();
        }
    }
}

【讨论】:

  • 你会如何使用 .hasNextLong 来代替?
  • 有什么理由必须使用 hasNextLong 而不是 try-catch 语句?
  • 这是一个作业,我们不应该使用课堂上没有教过的方法
  • 添加了 hasNextLong 声明,记得标记我为接受:)。
【解决方案2】:

一个简单的解决方案是使用异常。

int value;
do {
    System.out.print("Type a number: ");
    try {
        value = kbd.nextInt();
        break;
    }
    catch(InputMismatchException e) {
        System.out.println("Wrong kind of input!");
        kbd.nextLine();
    }
}
while(true);

【讨论】:

    猜你喜欢
    • 2018-05-30
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    相关资源
    最近更新 更多