2013-01-18 3 views
2

사용자가 입력 한 내용의 유효성을 검사하려고합니다. 사용자가 Y 좌표에 (AJ)와 X 사이에 문자를 넣습니다 (1 ~ 9). y 좌표는 유효하지만, x 좌표를 확인하는 데 문제가 있습니다. 사용자가 1에서 9 사이의 숫자 이외의 다른 값을 입력하면 사용자에게 유효한 입력을 계속 요청합니다.Java 정수 입력 유효성 검사

do { 
     // inner loop checks and validates user input 
     do { 

      System.out.println("Enter X Co-Ord (A-J), or Q to QUIT"); 
      letter = input.next().toUpperCase(); // upper case this for 
                // comparison 
      if (letter.equals("Q")) 
       break; // if user enters Q then quit 

      String temp = "ABCDEFGHIJ"; 

      while (temp.indexOf(letter) == -1) { 
       validString = false; 
       System.out.println("Please enter a valid input"); 
       letter = input.next().toUpperCase(); 
       col = temp.indexOf(letter); 

      } 

      if (temp.indexOf(letter) != -1) { 
       validString = true; 
       col = temp.indexOf(letter); 

      } 
      try { 

       System.out.println("Enter Y Co-Ord (0-9)"); 
       row = input.nextInt(); 


      } catch (InputMismatchException exception) { 
       validInt = false; 
       System.out.println("Please enter a number between 1 -9"); 
      } 

      catch (Exception exception) { 
       exception.printStackTrace(); 
      } 

      valuesOK = false; // only set valuesOK when the two others are 
           // true 
      if (validString && validInt) { 
       valuesOK = true; 
      } 
     } while (!valuesOK); // end inner Do loop 

출력은 :

는 X 공동 오드 (AJ)를 입력하거나, Q가 종료

D

는 입력 Y 공동 오드 (0-9)

h

1 -9

사이의 숫자를 입력하십시오.

당신은 당신이 때처럼 당신의 nextInt() 같은 주위에 while 루프를 둘 필요가 X 공동 오드 (AJ) 또는 Q가

입력 Y 공동 오드 (0-9)

+1

텍스트를 정렬하고 싶습니다. 하나는 0-9, 하나는 1-9라고 말합니다. –

답변

1

을 종료 입력 편지 읽기 : 인간의 눈 때문에,

System.out.println("Enter Y Co-Ord (0-9)"); 
    row = -1 
    while (row < 0) { 
    try { 
     row = input.nextInt(); 
     validInt = true; 
    } catch (InputMismatchException exception) { 
     System.out.println("Please enter a number between 1 -9"); 
     row = -1; 
     validInt = false; 
    } 
    } 
+0

이제 무한 루프로 들어간 것 같습니다 ... – user1899672

+0

편집 됨. 실수로 validInt 플래그를 떨어 뜨 렸습니다. –

+0

try catch에 대해 새로운 구문을 사용하십시오. 더 멋지게 보일 것입니다. –

0

그냥 검증을 할 요구 사항에 더 의미를 쉽게 라인을 건너 뛸 수 있습니다 nextInt()

String value = ""; 
System.out.println("Enter Y Co-Ord (1-9)"); 

while (!(value = input.next()).matches("[1-9]+")) { 
    System.out.print("Wrong input. Insert again: "); 
} 

System.out.println(value); 

물론 올바른 값을 얻으면 정수로 다시 구문 분석 할 수 있습니다. (안전하게 !!!)