2012-05-03 48 views
4

我正在写一个文件阅读器,这种想法是让用户输入一个数字,表示从文本文件中的行号循环。包含此号码的变量类型为int。但是,当用户输入一个String相反,Java的抛出InputMismatchException例外,我要的是有catch条款,在那里我会循环,直到用户输入一个有效的值,即一个int在一个循环。骨架看起来是这样的:爪哇 - 在try-catch块

public void _____ throws IOException { 
    try { 
    // Prompting user for line number 
    // Getting number from keyboard 
    // Do something with number 
    } catch (InputMismatchException e) { 
     // I want to loop until the user enters a valid input 
     // When the above step is achieved, I am invoking another method here 
    } 
} 

我的问题是,什么是可以做验证一些可能的技术? 谢谢。

回答

3

避免使用流量控制的异常。捕捉异常,但只打印一条消息。此外,确实需要循环内的循环。

它是如此简单:

public void _____ throws IOException { 
    int number = -1; 
    while (number == -1) { 
     try { 
      // Prompt user for line number 
      // Getting number from keyboard, which could throw an exception 
      number = <get from input>; 
     } catch (InputMismatchException e) { 
      System.out.println("That is not a number!"); 
     } 
    } 
    // Do something with number 
} 
+0

谢谢。这是有效的,但我必须在'catch'子句中的提示符之后添加一个额外的String ___ = __。nextLine()。 –

4
while(true){ 
    try { 
     // Prompting user for line number 
     // Getting number from keyboard 
     // Do something with number 
     //break; 
     } catch (InputMismatchException e) { 
      // I want to loop until the user enters a valid input 
      // When the above step is achieved, I am invoking another method here 
     } 
    } 
+3

你甚至不需要使用这个布尔变量。只要使用'while(true)'并在正确读取数据时打破循环。 – Yarg

+0

与Yarg同意7 而(真){ 尝试{// 提示用户的行号 //获取数从键盘 //使用数量 碰坏; }赶上(InputMismatchException时发送){// 我要循环,直到用户输入一个有效输入 //当实现上述步骤中,我调用另一个方法这里 } } –

+0

当我试图任一解决方案,我有一个无限循环。我正在寻找的是一种验证号码本身的方法。我正在考虑获取数字的ASCII值,如果它超出了适当的范围,则保持循环。 –

2

可以避开Exception

Scanner sc = new Scanner(System.in); 
while(sc.hasNextLine()) 
    String input = sc.nextLine(); 
    if (isNumeric(input) { 
     // do something 
     // with the number 
     break; // break the loop 
    } 
} 

的方法isNumeric

public static boolean isNumeric(String str) { 
    return str.matches("^[0-9]+$"); 
} 

如果你想使用的输入号码的对话框:

String input = JOptionPane.showInputDialog("Input a number:"); // show input dialog 
+0

谢谢你的帮助! –