gpt4 book ai didi

java - 如何在猜谜游戏中使用 JOption?

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:54 28 4
gpt4 key购买 nike

import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.*;

public class GuessingGameGUI {

public static void main(String[] args) {
Random rand = new Random();
int value = rand.nextInt(32) + 1;
int guesses = 0, LowGuess = 0, HighGuess = 0; //ADDED LowGuess AND HighGuess
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while (win == false) {
JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();
guesses++;
if (guess == value) {
win = true;
} else if (guess < value) {
JOptionPane.showInputDialog("Your guess is lower than random number");
LowGuess++; //COUNTER TO KEEP TRACK OF LOW GUESSES
} else if (guess > value) {
JOptionPane.showInputDialog("Your guess is higher than random number");
HighGuess++; //COUNTER TO KEEP TRACK OF HIGH GUESSES
}
}
JOptionPane.showMessageDialog(null, "You win! You are the worst guesser in history!");
JOptionPane.showMessageDialog(null, "The number was: " + value);

// ADDED FROM HERE (GUESSES)
JOptionPane.showMessageDialog(null, "Number of Guesses:" + guesses);
for (int x = 1; x <= guesses; x++) {
for (int a = 1; a <= guesses; a++) {
if (a == guesses) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // TO HERE FOR AMOUNT OF GUESSES

// I ADDED FROM HERE (LOW)
JOptionPane.showMessageDialog(null, "Smaller Guesses:" + LowGuess);
for (int Low_i = 1; Low_i <= LowGuess; Low_i++) {
for (int Low_e = 1; Low_e <= LowGuess; Low_e++) {
if (Low_e == LowGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} // Then TO HERE FOR LOW

// I ADDED FROM HERE (HIGH)
JOptionPane.showMessageDialog(null, "Largest Guesses:" + HighGuess);
for (int High_i = 1; High_i <= HighGuess; High_i++) {
for (int High_e = 1; High_e <= HighGuess; High_e++) {
if (High_e == HighGuess) {
JOptionPane.showMessageDialog(null, "*");
}
}
} //FINALLY TO HERE FOR HIGH
}
}

//当我运行我的程序时,当我输入猜测数字时,会弹出消息框,但是它似乎停止了,并且没有其他内容弹出来让我知道我猜测的是高还是低。

最佳答案

以这些行为例:

JOptionPane.showInputDialog("Guess a number between 1 and 32: ");
guess = input.nextInt();

将显示一条提示,要求您“猜测 1 到 32 之间的数字”。因此,您输入数字,然后执行停止,因为您的扫描仪正在等待您的输入。您需要完全删除扫描仪,这样您就不会遇到这些频繁的中断。

JOptionPaneshowInputDialog 方法返回一个 String,如 Javadocs 中的示例所示。 :

Show a dialog asking the user to type in a String:

String inputValue = JOptionPane.showInputDialog("Please input a value");

事实上,当您应该将方法返回的值分配给变量时,您就丢弃了该值。为了将返回值分配给 int 变量 guess,请使用 Integer.parseInt:

guess = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and 32: "));

关于java - 如何在猜谜游戏中使用 JOption?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28568202/

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