2013-10-27 19 views
1

所以我正在嘗試在高中時爲我的課程創建一個程序,以便能夠生成一個隨機數並讓用戶在猜對之前一直保持猜測。如何重置java中for循環的計數器

到目前爲止,除了當我提示他們再次參加比賽時,我已經完成了一切,除了他們選擇再次參加比賽之後,他們已經猜到了多少次的計數器沒有重置。我不知道該怎麼做,並尋找解決方案,這對我來說太難理解或使用。

請注意,這只是我編程的第二個月,所以代碼看起來可能是業餘的,而且在編程時我可能看起來很糟糕。我只需要一個解決方案,也許還有一個解釋。

import javax.swing.JOptionPane; 
import java.util.Random; 
import javax.swing.UIManager; 
import java.awt.*; 

public class RandomNumberGuesser{ 
    public static void main(String[] args){ 
     UIManager m1=new UIManager(); 
     Color g = Color.gray; 
     Color lg = g.brighter(); 
     m1.put("OptionPane.background", lg); 
     m1.put("Panel.background", lg); 

     for(x = 1; true; x++){ 
     Random random = new Random(); 
     int randomNumber = random.nextInt(100); 

     JOptionPane.showMessageDialog(null, 
      "This program will generate a random number from 0 to 100 which you have to guess.", 
      "Number Guesser", 
      JOptionPane.INFORMATION_MESSAGE); 
      String guess = JOptionPane.showInputDialog(null, 
       "Guess a number.", 
       "Guess", 
       JOptionPane.QUESTION_MESSAGE); 
       if(guess == null){ 
        System.out.println("The user has terminated the program"); 
        System.exit(0); 
       } 
      int guess1 = Integer.parseInt(guess); 

      if(guess1 > 100 || guess1 < 0) 
       JOptionPane.showMessageDialog(null, 
        "Guess is out of range!\nPlease enter valid input.", 
        "Invalid Input", 
        JOptionPane.WARNING_MESSAGE); 

      else if(randomNumber > guess1) 
       JOptionPane.showMessageDialog(null, 
        "You guessed too low.\nGuess again!", 
        "Your guess", 
        JOptionPane.INFORMATION_MESSAGE); 

      else if(randomNumber < guess1) 
       JOptionPane.showMessageDialog(null, 
        "You guessed too high.\nGuess again!", 
        "Your guess", 
        JOptionPane.INFORMATION_MESSAGE); 

      else if(randomNumber == guess1){ 
       JOptionPane.showMessageDialog(null, 
        "You guessed the number right!\nIt took you "+x+" attempt(s) to guess it.", 
        "Congratulations!", 
        JOptionPane.INFORMATION_MESSAGE); 
       if (JOptionPane.showConfirmDialog(null, "Want to play again?", "Play again?", 
         JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) { 
        System.exit(0); 
       } 

      } 

     } 
    } 
} 

回答

1
if (JOptionPane.showConfirmDialog(
        null, 
        "Want to play again?", 
        "Play again?", 
        JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) { 
    System.exit(0); 
} else { 
    x = 1; 
} 

只是將計數器復位到其初始值。

請注意,您應該避免在每次迭代中創建一個新的Random對象。在循環之外創建一次,每次只需撥打random.nextInt(100)

+0

這麼簡單,但卻是一種救命。謝謝! – Auxive

+0

我認爲「Not that ...」必須是「請注意......」,但我無法編輯它,因爲編輯必須有六個字符。 – Teetrinker

+0

@Teetrinker:改變它:) –

0

在開始迭代之前的循環結束時,只在計數器啓動之前將計數器初始化爲初始值。 這確保了在每個循環中計數器的值是初始位置

counter=0;