我正在尝试编写一个 while 循环(不是 do...while),一旦用户在 showConfirmDialog 窗口上单击“否”,该循环就会退出。但是,当我运行程序时,即使我单击“否”或尝试退出,它也会不断迭代循环。我怀疑这是因为我无法让 yesNO 变量等于 JOptionPane.NO_ANSWER,即使当我单击 No... 时它应该变成 NO_ANSWER 对?
我存储在变量 rand 和 number 中的 SecureRandom 代码不会在 answers 数组中生成随机数。我试过 Math.random() 但它没有用,但我想使用 SecureRandom 来生成随机数组索引。
我的 while 循环的最后一行没有用空字符串替换 userInput 值。它只是在输入第一个问题的情况下迭代循环。所以即使我想留在那个无限循环中,它甚至不会记录我输入的新问题......
我怎样才能让它在用户单击否时退出循环,SecureRandom 代码每次都会生成不同的答案索引(目前它只显示索引 19 非常可疑),并且 userInput 变量被更改为空白字符串?或至少用下一次迭代的输入替换当前字符串
import javax.swing.*;
import java.math.*;
public class MagicEightBall {
public static void main(String[] args) {
Random rand = new SecureRandom();
int number = rand.nextInt(20);
//array for answers
String [] answers = {"It is certain", "It is decidedly so", "Without a doubt",
"Yes - definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes",
"Yes", "Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now", "Concentrate and ask again",
"Don't count on it", "My reply is no", "My sources say no",
"Outlook not so good", "Very doubtful"};
ImageIcon image = new ImageIcon("8ball_small.jpg");
// prompt user for question
String userInput = JOptionPane.showInputDialog(null, "What is your question?", "Welcome to MAGIC 8-BALL", JOptionPane.QUESTION_MESSAGE);
//return answer (Always returns "Very Doubtful)
showMessageDialog(userInput + "\n\n\n\n" + answers[number],"MAGIC 8-BALL SAYS: ",0,image);
int yesNo = showConfirmDialog("","ASK MAGIC 8-BALL AGAIN", JOptionPane.YES_NO_OPTION, 0, image);
// ask user to stop or continue asking questions (begins loop no
//matter what input)
while (yesNo == JOptionPane.YES_OPTION) {
userInput = JOptionPane.showInputDialog(null, "What is your question?", "Welcome to MAGIC 8-BALL", JOptionPane.QUESTION_MESSAGE);
showMessageDialog(userInput + "\n\n\n\n" + answers[number],"MAGIC 8-BALL SAYS: ",0,image);
yesNo = showConfirmDialog("","ASK MAGIC 8-BALL AGAIN", JOptionPane.YES_NO_OPTION, 0, image);
userInput = ""; // doesn't reset userInput to an empty string for
// next iteration
}
showMessageDialog("/n/n/n/n Programmed By Jason Silva","GOODBYE ",0,image);
}
//teacher wants us to write methods for the dialog boxes
public static void showMessageDialog(String message, String title, int messageType, ImageIcon image) {
JOptionPane.showMessageDialog (null, message, title, messageType, image);
}
public static int showConfirmDialog(String message, String title,
int optionType, int messageType, ImageIcon icon) {
JOptionPane.showConfirmDialog(null, message, title, optionType, messageType, icon);
return optionType;
}
}