Search code examples
javawhile-loopdo-whiledo-loops

Try Again Do-While Loop


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!!"); 

Solution

  • 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"