2013-10-23 115 views
-1

如何在输入非数字值时阻止程序崩溃?我知道kbd.hasNextLong,但我不确定如何实现它。验证Java中的扫描仪输入

+0

参见:http://stackoverflow.com/questions/19552811/why-does-this-while-loop-work/19552848#comment29014062_19552848 – Origineil

+0

你能张贴清晰一些代码? – aboger

+0

在OP – Spork

回答

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()在追赶声明。如果你输入一些非int文本,它会跳转到catch(导致Integer不能在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(); 
     } 
    } 
} 
+0

的代码如何使用.hasNextLong来代替? – Spork

+0

你有什么理由不得不使用hasNextLong代替try-catch语句吗? – libik

+0

这是一个任务,我们不应该使用类 – Spork

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