2014-10-09 40 views
0

我試圖計算一個玩家玩固定金額的樂透和小丑遊戲可以玩多少回合。在Java中循環中減去一個變量

public static void example() { 
    int money = 200; 
    int lottoCost = 4; 
    int jokerCost = 3; 
    int costTogether = lottoCost+jokerCost; 
    int rounds = 0; 

    for (int i = money; i <= 0; rounds++) { 
     money = money-costTogether; 
    } 

    System.out.println("With " + money + " euros, you can play " 
         + rounds + " rounds."); 
    System.out.println(""); 

} 

該代碼當前打印的文本「200歐元,你可以玩0回合。」 因此,它不會爲變量添加+1。我究竟做錯了什麼?

+0

循環從未輸入,這就是爲什麼你看到你所看到的。 – Bala 2014-10-09 10:48:03

+4

嘗試在紙上進行for-loop。 – 2014-10-09 10:49:28

+0

爲什麼使用for循環? – Sambuca 2014-10-09 10:50:26

回答

2

你停止條件是錯誤的,因此該循環永遠不會exectued。您應該使用>=。此外,你永遠不會改變也不會使用i

這裏是一個更正的版本,使用的currMoney代替i更有意義。

int rounds = 0; 
for (int currMoney = money; currMoney >= costTogether; currMoney -= costTogether) { 
    rounds++; 
} 

但顯然在這裏,你只需要一個簡單的劃分爲@Fredszaq在他的回答中指出:

int rounds = money/costTogether; 
+0

貨幣變量不應該改變,因爲它稍後會打印出來。 – Sambuca 2014-10-09 10:55:30

+1

確實,我以爲OP是在打印剩下的錢,我沒看過;-) – Joffrey 2014-10-09 10:57:52

+0

這的確有竅門!當然,我想要一個新的變量:)感謝大家真正快速的答案! – user1589375 2014-10-09 11:01:02

0

for -loop未正確定義。 i開始於money = 200.只要i <= 0您想要重複循環。所以你需要我從200開始,而不是大於0.這就是爲什麼你的循環根本不被執行。

而是喜歡while循環爲你的情況。這是更具可讀性:

while (money >= costTogether) { 
    money = money - costTogether; 
    rounds++; 
} 

如果你想使用一個for循環,你可以聲明它像:

for (int i = money; i >= costTogether; i -= costTogether) { 
    rounds++; 
} 
+0

他正在做'我<= 0'? – 2014-10-09 10:48:56

+0

這就是他的代碼所說的。無論如何,使用for循環似乎不太適合他的情況。 – 2014-10-09 10:52:30

0

這種情況i <= 0是不正確的,可能不得到增加

我猜它的一個錯字,

大和每種不超過你需要的,因爲他們改變上下文知道。

+0

雖然無限循環。 – 2014-10-09 10:49:59

+0

@Evan oops!我沒有看到它,謝謝。隨時更新,以清除它 – 2014-10-09 10:50:44

-1

你只是增加rounds,以一種迂迴的方式,循環運行時。

循環運行時,i <= 0-i開始等於money,這等於200,所以循環從不運行,循環值不增加。

你也沒有改變i在循環中 - 我懷疑你寧願要,而i >= 0和遞減i在循環?

for (int i = money; i >= 0; rounds++) { 
    money = money-costTogether; 
    i--; 
} 
+0

這是錯誤的。 '我'從'金錢'開始,但不會在每一回合減少適量。 – Joffrey 2014-10-09 10:51:49

4

通常,在for的3部分中使用相同的變量是很好的。請注意,循環初始化部分(第一個int i = money)只運行一次,並且在循環過程中不會修改i。此外,該條件是從一開始(200 < 0)假所以循環甚至沒有運行一次

我想你正在尋找的是一個簡單的INT師,只是這個替換你的塊:

rounds = money/costTogether; 
+1

Upvoted爲原始問題的簡單答案,而不是OP的當前小錯誤。 – Joffrey 2014-10-09 11:03:38