showConfirmDialogウィンドウでユーザーが「いいえ」をクリックすると終了するwhileループ(Not a do ... while)を書き込もうとしています。しかし、プログラムを実行すると、[いいえ]をクリックしても、ループを繰り返して終了します。これは、NoNO変数をJOptionPane.NO_ANSWERに等しくすることができないためです.No_ANSWERをクリックしたときにNO_ANSWERになるはずですが、これは正しいですか?ユーザーが「いいえ」をクリックしたときにJOptionPaneのループを終了する方法は?
変数randとnumberに格納されている私のSecureRandomコードは、answers配列に乱数を生成していません。私はMath.random()を試してみましたが動作しませんでしたが、SecureRandomを使用してランダム配列インデックスを生成したいと考えています。
私のwhileループの最後の行は、userInputの値を空のStringに置き換えているわけではありません。入力した最初の質問でループを繰り返すだけです。その無限ループにとどまりたいと思っても、私が入力した新しい質問は記録されません。
ユーザーが「いいえ」をクリックすると、SecureRandomコードが生成されます(現在はインデックス19 Very Doubtfulのみを表示しています)、userInput変数は空のStringに変更されますか?または少なくともあなたのshowConfirmDialog
方法は、常に常にあるoptionType
を返し
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;
}
}
rand.nextIntを()私のwhileループであり、それは数変数にあります –