用消息提示框来进行猜数字游戏(范围:1~100)
public class GuessNumber {
public static void main(String[] args) {
// 存储随机数
int realNumber, guess;
// 产生一个1~100的随机数
realNumber = (int) (Math.random() * 100 + 1);
// 提示是否进入游戏
int choice = JOptionPane.showConfirmDialog(null, "是否进入 ", null, JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
// 输入
guess = Integer.parseInt(JOptionPane.showInputDialog(null, "please input num"));
while (true) {
if (guess == realNumber) {
JOptionPane.showMessageDialog(null, "猜对了");
break;
} else if (guess > realNumber) {
guess = Integer.parseInt(JOptionPane.showInputDialog(null, "大了,请重新输入"));
continue;
} else {
guess = Integer.parseInt(JOptionPane.showInputDialog(null, "小了,请重新输入"));
continue;
}
}
}
}
}
运行: