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 に答える