【发布时间】:2015-03-14 22:42:54
【问题描述】:
您好,请有人帮帮我。我正在编写一个程序,用户可以在其中输入猜谜游戏的最大数字,并使用随机生成器他/她必须从 1 到最大数字猜测数字。我已经完成了大部分工作,但是如果用户说输入一个字母或除整数之外的任何其他内容,我会陷入如何循环程序以输入另一个输入的问题。从“做”部分是我感到困惑的地方!
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class guessinggame { // class name
public static void main(String[] args) { // main method
String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
int max = Integer.parseInt(smax);
do {
if (max > 10000) {
JOptionPane.showMessageDialog(null, "Oh no! keep your choice below 10000 please.");
smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
max = Integer.parseInt(smax);
}
} while (max > 10000);
int answer, guess = 0, lowcount = 0, highcount = 0, game;
String sguess;
Random generator = new Random();
answer = generator.nextInt(max) + 1;
ArrayList<String> buttonChoices = new ArrayList<String>(); // list of string arrays called buttonChoices
buttonChoices.add("1-" + max + " Guessing Game");
Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons
game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
null, buttons, buttonChoices.get(0));
do {
sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
try {
guess = Integer.parseInt(sguess);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
break;
} while (guess != answer);
JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
+ "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");
System.exit(0);
}
}
【问题讨论】:
-
获取输入,进入
while(input.isNotValid) getInput- 或类似的...如do { getInput } while (input.isNotValid)。 -
该死,这是 Java,不是 JavaScript!它们是有区别的!我无法从 iOS 更改标签,请其他人这样做,以便问题正确分组。
-
我不明白你的意思首席
-
格式化您的代码,使其易于阅读,我会看看它。在这一点上太草率了,无法打扰它。完成后与@Chief 联系我。
-
@ChiefTwoPencils 兄弟,非常感谢!
标签: java loops if-statement joptionpane do-while