gpt4 book ai didi

java - 如何重置java中for循环的计数器

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:41 25 4
gpt4 key购买 nike

因此,我正在尝试为我的高中类(class)创建一个程序,以便能够生成随机数并让用户不断猜测,直到他们猜对为止。

到目前为止,我一切都很顺利,除了当我提示他们再次玩时,计算他们猜测次数的计数器在他们选择再次玩后不会重置。我不知道该怎么办,寻找解决方案,对我来说太复杂,无法理解或使用。

请注意,这只是我编程的第二个月,因此代码可能看起来很业余,而我的编程能力可能看起来很糟糕。我只需要一个解决方案,也许还需要一个解释。

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);
}

}

}
}
}

最佳答案

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) 即可。

关于java - 如何重置java中for循环的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com