0

我有一个代码

  boolean playerTakesAHit() throws IOException {
  char ch = ' '; boolean hit=false;
  do{
   System.out.print("Hit or Stay: "); 
   System.out.flush();
   String playersDecision = keyboardInput.readLine(); 
   try {ch = playersDecision.charAt(0);
   } catch (StringIndexOutOfBoundsException exception) {
   if(ch == 'H' || ch == 'h') {
           return true;
       }
   if(ch == 'S' || ch == 's') {
           return false;
       }}
  } while(true);

我想要的是这个方法会在用户点击 H/h(返回 true)时重复,并在用户点击 S/s 时立即停止。但是当我使用以下方法调用此方法时:

 ...
 while(playerTakesAHit()) {
  System.out.println("Player Hit"); 
 }
 ...

我得到了这样的东西:

击中或留下:h

击中或留下:h

击中或留下:s

击中或留下:S

击中或留下:

无论用户输入什么,它都会重复询问 Hit 或 Stay。有人知道我的错误在哪里吗?

4

1 回答 1

0

尝试这个:

  char ch = ' '; 
  boolean hit=false;
  do{
      System.out.print("Hit or Stay: "); 
      System.out.flush();
      String playersDecision = keyboardInput.readLine(); 
      try {
          ch = playersDecision.charAt(0);
      } catch (StringIndexOutOfBoundsException exception) {
          ch = ' '; //blank out
      }
      if(ch == 'H' || ch == 'h') {
         hit = true;
      }
    } while(!(ch == 'S' || ch == 's'));
    return hit;
于 2012-12-26T03:17:21.560 回答