2015-03-31 57 views
-1

import java.util。*;如何重複我的代碼特定次數的java?

公共類guessingGame

{

靜態掃描儀控制檯=新掃描儀(System.in);

public static void main(String[] args) 

{ 
     int random, up=0, down=0, x=3, guess=0, nop; 


     System.out.println(" Please enter an upper bound number! "); 

     up = console.nextInt(); 

     System.out.println(" Please enter a lower bound number! "); 

     down = console.nextInt(); 



     nop = (up - down) - 1 ; 

     random = (int)(Math.random() * (nop)) + (down); 




     do { 

     System.out.println(" Please guess a number between " + up + " and " + down); 

     guess = console.nextInt(); 

     if(guess == random) 

     System.out.println("You guessed the right number! CONGRATULATIONS!"); 

     else if(guess < random) 

     System.out.println("Sorry you should guess higher! Try again!"); 

     else if(guess > random) 

     System.out.println("Sorry you should guess lower! Try again!"); 

     x--; 

     } 

     while(x>0); 


    } 

}

運行guessingGame 請輸入一個上限數字! [DrJava輸入框] 請輸入下限數字! [DrJava輸入框] 請猜數字3和1之間 [DrJava輸入框] 對不起,你應該猜測更低!再試一次! 請猜數字3和1之間 [DrJava輸入框] 你猜對了數字!恭喜! 請猜數字3和1之間 [DrJava輸入框] 對不起,你應該猜測更低!再試一次!

我現在的問題是我的循環仍然繼續,即使我得到正確的答案。我還有一個關於如何詢問用戶是否想要重放遊戲的大腦放屁,我不知道如何去做。

回答

1

你應該讓x = 0時,如果用戶猜測正確的答案在你的if語句

if(guess == random){ 

     System.out.println("You guessed the right number! CONGRATULATIONS!"); 
x = 0; 
} 
1

添加標誌要記住,如果你找到了一個匹配:

public static void main(String[] args) 

{ 
    int random, up=0, down=0, x=3, guess=0, nop, found = 0; 


    System.out.println(" Please enter an upper bound number! "); 

    up = console.nextInt(); 

    System.out.println(" Please enter a lower bound number! "); 

    down = console.nextInt(); 



    nop = (up - down) - 1 ; 

    random = (int)(Math.random() * (nop)) + (down); 




    do { 

    System.out.println(" Please guess a number between " + up + " and " + down); 

    guess = console.nextInt(); 

    if(guess == random){ 

    System.out.println("You guessed the right number! CONGRATULATIONS!"); 
    found = 1; 
    } 

    else if(guess < random) 

    System.out.println("Sorry you should guess higher! Try again!"); 


    else if(guess > random) 

    System.out.println("Sorry you should guess lower! Try again!"); 

    x--; 

    } 

    while(x>0 && found == 0); 


} 
+0

謝謝!這有很大幫助。還有什麼建議,我可以問用戶,如果他們想再玩一次?重複「遊戲」。 – 2015-03-31 03:30:31