2016-01-20 54 views
-2

我該如何限制一個簡單遊戲的嘗試只有三個?我想你會使用布爾值。但不確定。嘗試進行簡單遊戲的次數有限?

import java.util.Scanner; 

public class guess { 

    public static void main(String[] args) { 
     int randomN = (int) (Math.random() * 10) + 1; 

     Scanner input = new Scanner(System.in); 
     int guess; 
     System.out.println("Enter a number between 1 and 10."); 
     System.out.println(); 

     do { 
      System.out.print("Enter your guess: "); 
      guess = input.nextInt(); 

      if (guess == randomN) { 
       System.out.println("You won!"); 
      } else if (guess > randomN) { 
       System.out.println("Too high"); 
      } else if (guess < randomN) { 
       System.out.println("Too low"); 
      } 
     } while (guess != randomN); 
    } 
} 
+0

您需要爲已經取得的嘗試次數的計數器,你需要增加對循環的每個迭代的計數器,你需要一個額外的退出條件添加到您的'做-while'環 – MadProgrammer

回答

1
int attempts = 0; 
do{ 
    attempts++; 
    .... 
}while(guess != randomN && attempts < 3); 
0

使用的標誌。將其初始化爲0.如果猜測正確,則將其重置爲0.如果不是1,則在每次猜測之前,檢查標記> 2。如果不允許繼續,則如果是中斷。

-1

您可以在猜測失敗時遞增。我相信變量應該位於循環之外。然後剩下的就是添加一部分,當猜測用完時通知用戶失敗。

public static void main(String[]args) { 
    int rNumber = (int)(Math.random() * 10) + 1; 
    Scanner input = new Scanner(System.in); 
    int guess; 
    int tries = 0; 
    int success = 0; 

    System.out.println("Enter a number between 1 and 10."); 
    System.out.println(); 
    do { 
     System.out.println("Enter your guess: "); 
     guess = input.nextInt(); 
     if(guess == rNumber) { 
      System.out.println("You guessed right! You win!"); 
      success++; 
     } else if (guess < rNumber) { 
      System.out.println("Too low"); 
      tries++; 
     } else if (guess > rNumber) { 
      System.out.println("Too high."); 
      tries++; 
     } 
    } while(tries != 3 && success != 1 || success != 1); 

} 
+0

這代碼將僅在第一次猜測正確時退出... – sinclair

+0

好點。我太倉促了。 – sunnlamp

+0

現在它會繼續如果你猜對了;-) – sinclair