2012-05-03 5 views
4

나는 파일 판독기를 쓰려고하는데, 사용자가 텍스트 파일의 줄 번호를 나타내는 숫자를 입력하게하는 것이 좋습니다. 이 숫자를 보유하는 변수의 유형은 int입니다. 그러나 사용자가 String을 입력하면 자바에서 InputMismatchException 예외가 발생하고 사용자가 유효한 값인 int을 입력 할 때까지 루프가 반복되는 catch 절에 루프가 있어야합니다. 해골 모양은 다음과 같습니다.try - catch 블록에서 Java 루핑하기

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 static boolean isNumeric(String str) { 
    return str.matches("^[0-9]+$"); 
} 

당신이 입력 번호에 대한 대화 상자를 사용하려면 다음

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' 절의 프롬프트 다음에 추가 문자열 ___ = __. 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에 – Yarg

+0

동의 7 동안 (사실) { 시도 { // 라인 번호 사용자에게 메시지를 표시 // 키보드 에서 수를 얻기 // 수 휴식 뭔가를 수행; 사용자가 올바른 입력을 입력 할 때까지 } 캐치 (InputMismatchException 전자) { 가 // I 루프로 할 상기 단계가 달성되면 나도 용액을 시도하면, 여기 } } –

+0

다른 메소드를 호출하고 // I 무한 루프가 있습니다. 내가 찾고 있던 것은 번호 자체를 검증하는 방법이다. 숫자의 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을 방지 할 수 있습니다

그것은이처럼 간단합니다 :

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

도움 주셔서 감사합니다. –

관련 문제