2016-12-07 98 views
-1

我的代碼是猜謎遊戲。當用戶用完猜測或猜測幻數時,我應該問他們是否想再次猜測一個數字。只要用戶不輸入哨兵,它應該能夠運行1000次,這是「否」。我需要讓我的代碼循環到它將繼續前進的位置,直到用戶說「不」爲止。如何創建一個循環,直到輸入一個哨兵?

我試圖在我的代碼的底部要做到這一點,但卡住了,因爲我覺得我應該已經做了一些在一開始,使之成爲環......有人告訴我,我應該怎樣包括這我的代碼?

+1

這是一個你需要的簡單循環。只需循環輸入您的實際代碼,直到輸入關鍵字('否')。這就是爲什麼方法在這裏是一個好主意。你的遊戲應該是一種方法,你的主要只會有一個循環,而要求再次玩,並調用'game()'方法 – AxelH

+2

請參閱http://stackoverflow.com/questions/513832/how-do-i -compare串式的Java。我們沒有任何事情可以幫助您循環,直到您正確地進行字符串比較爲止。 – ajb

+1

@ScaryWombat我不同意重複,是的,字符串比較存在問題,但OP不知道如何創建該循環。所以主要問題(對他來說)將不會以重複方式回答,只會產生副作用。 – AxelH

回答

2

你需要下面給出通過循環運行:

final String SENTINEL = "no"; 

# put your required code here 

System.out.print(" Would you like to try to guess a number? (Yes or No):"); 
String answer = scan.next(); 

while(!answer.equals(SENTINEL)){ 
    # put your required code here 

    # do all your stuff and then ask users' preference again 
    System.out.print("Would you like to try to guess a number? (Yes or No):"); 
    answer = scan.next(); 
} 

您還可以使用做,而環路,更好地匹配您的需要。

final String SENTINEL = "no"; 
# put your required code here 
System.out.print(" Please enter your name: "); 
String name = scan.next(); 

do{ 
    # put your required code here 

    # do all your stuff and at the end of the loop ask users' preference 
    System.out.print("Would you like to try to guess a number? (Yes or No):"); 
    String answer = scan.next(); 
}while(!answer.equals(SENTINEL)); 

之間的差做-而是,DO-而在循環,而不是頂部的底部評估其表達。因此,do塊中的語句總是至少執行一次。

+0

我將在最後居然用一個做,而只與問題;)這是完美的使用 – AxelH

+0

我同意。 do-while循環最適合OP的場景。 –

+0

我冒昧地編輯答案,你在循環中問了兩次這個問題,但你只需要在最後一次提問之前提問。 PS:你應該解釋一下條件;) – AxelH