2

It is a very simple program. The computer and user chooses a number between 0-3. I want the program to loop back if the user does not guess the same number as the computer.

    String input; // input is a string variable
    int cpucrazy;
    int convertstring; 

// First Step //

    input = JOptionPane.showInputDialog("Guess a number between 0-3");
    convertstring = Integer.parseInt(input);

// Random section //

    Random ran = new Random ();
    cpucrazy = ran.nextInt(3);

// computation!

if (cpucrazy < convertstring) {
     JOptionPane.showInputDialog(null, "Your guess is too high. Guess again?"); }


else if (cpucrazy > convertstring) {
     JOptionPane.showInputDialog(null, "Your guess is too low. Guess again?"); }


else JOptionPane.showMessageDialog(null, "Correct!!"); 
luckyruby1
  • 51
  • 1
  • 8
  • 1
    Please elaborate on the problem that you faced. – Kunal Puri Jan 12 '19 at 00:33
  • 2
    You'll want to pick your random number _before_ asking for input, then ask for input, do your comparisons, and show your message dialog all within a `do { ... } while (convertstring != cpucrazy)` loop – Stephen P Jan 12 '19 at 00:35
  • The do-while loop did work as you mentioned. However, the computer changes the number when it loops. I want the computer to remember the number and allow the user to keep guessing. – luckyruby1 Jan 12 '19 at 00:52
  • @ninjacoder Look at my answer. You will see that to avoid the computer from picking a new number you have it pick a number *before* entering the loop. Inside the loop you only get input from the user and compare the two numbers. – Chimera Jan 12 '19 at 00:55

1 Answers1

1
if (cpucrazy < convertstring) {
 JOptionPane.showInputDialog(null, "Your guess is too high. Guess again?"); }


else if (cpucrazy > convertstring) {
     JOptionPane.showInputDialog(null, "Your guess is too low. Guess again?"); }


else JOptionPane.showMessageDialog(null, "Correct!!"); 

You need to put a while loop ( or some type of looping construct ) around the above code and exit the construct when: cpucrazy == convertstring or stay in the loop construct while cpucrazy != convertstring

The loop could look like the following pseudo-code:

b = random();

do
{
     input a;
     if( a != b )
     {
         if(a < b )
         {
              print "Too low";
         }
         else
         {
              print "Too high";
         }
     }
} while( a != b );

print "You got it correct"
Chimera
  • 5,884
  • 7
  • 49
  • 81