2016-12-25 108 views
-5

我正在嘗試製作一個遊戲,用戶有3次機會猜測程序生成的隨機數。到目前爲止,我有這個代碼,但是我不知道如何在用戶輸入3個猜測中的3個後停止程序。如果用戶不能在3次嘗試猜,我希望該計劃說:「你鬆,號碼是......」限制猜謎遊戲三次嘗試

import java.util.Random; 
import java.util.Scanner; 
class GuessNumber { 
    public static void main(String args[]) { 
     Random random = new Random(); 
     Scanner input = new Scanner(System.in); 
     int MIN = 1; 
     int MAX = 10; 
     int comp = random.nextInt(MAX - MIN + 1) + MIN; 
     int user; 


     do { 
      System.out.print("Guess a number between 1 and 10: "); 
      user = input.nextInt(); 

      if (user > comp) 
       System.out.println("My number is less than " + user + "."); 
      else if (user < comp) 
       System.out.println("My number is greater than " + user + "."); 
      else 
       System.out.println("Correct! " + comp + " was my number! "); 
     } while (user != comp); 
    } 
} 
+1

您需要一個計數器變量,在每次嘗試時增加它,並在/如果計數器達到3時打印並退出。 – Andreas

回答

0

簡單地計算嘗試的次數,一旦它到達退出循環門檻。像這樣:

int attemptsNum = 0; 
    final int maxAttempts = 3; 
    do { 
     System.out.print("Guess a number between 1 and 10: "); 
     user = input.nextInt(); 

     if (user > comp) 
      System.out.println("My number is less than " + user + "."); 
     else if (user < comp) 
      System.out.println("My number is greater than " + user + "."); 
     else 
      System.out.println("Correct! " + comp + " was my number! "); 
    } while (user != comp && ++attemptsNum <maxAttempts); 

    if (attemptsNum == maxAttempts) 
     System.out.println("You loose. The number was :" + comp);