|
This program is to write a Java main class to play a number guessing game. The user thinks of a number between 1 and 128 and the computer guesses the number by asking several yes/no questions. The program's main class should:
- Use JOptionPane to tell the user to think of a numer between low = 1 and high = 128 - Start a while loop - Guess at the number by calculating the number half way between low and high, (low+high)/2 - Use JOptionPane to ask the user if your guess is correct; yes or no - If the answer is yes the break from the loop - If the answer is no then ask the user if your guess is bigger than the nunber, yes or no - Depending on the answer adjust low or high - End the while loop - Display the correct guess and the number of guesses
-------------------------------------------------------------------------------- import javax.swing.JOptionPane;
public class game { public game() { int low = 1, high = 128, guess = 0; String check = "", check2; boolean check3 = true; JOptionPane.showMessageDialog(null,"Think of a number between 1 and 128");
while(true){ guess = (low + high)/2; check = JOptionPane.showInputDialog("Is your number " + guess +"? (y/n)"); if(check.equalsIgnoreCase("Y")){ JOptionPane.showMessageDialog(null, "The number you guessed is "+ guess); check3 = false; break; } else if (check.equalsIgnoreCase("N")){ check3 = true; check2 = JOptionPane.showInputDialog("Is the number greater than or less than "+ guess+"? (< >)"); if(check2.equals("<")) //less than high = guess; else if(check2.equals(">")) // greater than low = guess; } else check = JOptionPane.showInputDialog("Please specify (Y or N):"); } }
public static void main(String[] args) { new game(); }
|