2013-01-18 133 views
2

我想验证来自用户的输入。用户在(AJ)和x坐标之间放置一个字母Y坐标(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之间的数字

输入X联合奥德(AJ),或Q退出

输入Y共同奥德(0-9)

+1

你会想对齐你的文本;一个说0-9,一个说1-9。 –

回答

1

你只需要把一个while循环在你nextInt()和你一样做的时候看完信:

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

请尝试使用新的语法,它会看起来更好。 –

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

当然,当你得到正确的价值,那么你可以再次解析它为整数(安全!!!)