-1

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

4

2 回答 2

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();
        }
    }
}
于 2013-10-23T22:27:32.013 回答
-1

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

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);
于 2013-10-23T22:40:18.363 回答