私は数を絶えず推測し、数字が高すぎるか低すぎるかをユーザーに尋ね、正しい数字を推測するまで推測を調整しようとしています。ユーザーはプログラムが正しい番号を見つけたと言います。次に、数を推測するのに何回かを返します。カスタムボタンを使って数字を推測するゲームを作る
私の問題は、私はのJOptionPaneで推測
public static void main(String[] args) {
int result;
String setUpper = JOptionPane.showInputDialog("Please set the upper bound");
Scanner input;
input = new Scanner(setUpper);
int upperBound;
upperBound = input.nextInt();
int [] guessArray = new int[upperBound];
int left; // Left edge of the unsearched portion
int right; // just past right edge of unsearched portion
left = 0;
right = guessArray.length;
counter = 0;
JOptionPane.showMessageDialog(null, "Alright, I'll find the number you picked, from 0 to " + guessArray.length, "Output", JOptionPane.INFORMATION_MESSAGE);
Object[] options = {"Too low", "You got it!", "Too high"};
result = JOptionPane.showOptionDialog(null, "Is your number " + (guessArray.length/2), "Guess",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
while (left != right-1) { // while left, right not adjacent
int mid = (right+left)/2;
counter++;
//guessArray[mid];
if (result == JOptionPane.YES_OPTION) { // it's to the left
right = mid;
}
else {
if (result == JOptionPane.CANCEL_OPTION) {
left = mid;
}
else {
if (result == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, "It took " + counter + " comparisons to find your number",
"Output", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
}