1

Okay so my code works, however if the user correctly guesses "blue", the line prints "you got the right color!". Then the code should end. However, it brings up another a k.next(); line. How can I prevent this? If you do not understand, here is the code.

import java.util.Scanner;

public class BEassignment11
{
  public static void main (String [] args)
  {
    Scanner k = new Scanner (System.in);
    String color;
    String again;
    
    do 
    {
      
      System.out.println ("Try to guess my favorite color!");
      color = k.next();
      
      if  (color.equalsIgnoreCase ("blue"))
      {    
        System.out.println ("You got the right color!");
        
      }
      
      else
      
        System.out.println ("That is not the right color. Would you like to try again? Yes/No"); 
        again = k.next();
    }
    while (again.equalsIgnoreCase ("yes"));
    
  }
}
boroboris
  • 1,548
  • 1
  • 19
  • 32
B. Eaton
  • 15
  • 4
  • just break out of the loop.by the way be consistent with your `{}` in if-else – Ramanlfc Mar 29 '17 at 18:34
  • 1
    Possible duplicate of [Break DO While Loop Java?](http://stackoverflow.com/questions/7370174/break-do-while-loop-java) – Satpal Mar 29 '17 at 18:34

3 Answers3

0

You can just break out of the loop with the "break" statement like this:

if  (color.equalsIgnoreCase ("blue")){    
    System.out.println ("You got the right color!");
    break;
}
DZDomi
  • 1,685
  • 15
  • 13
0

You can use break following System.out.println ("You got the right color!"); within if statement at do..while loop.

Or define a variable before do..while loop, for example var boolFlag = false set variable to true within if statement boolFlag = true, include || boolFlag === true within while condition.

guest271314
  • 1
  • 15
  • 104
  • 177
0

System.out.println.... is part of the else clause. You seem to be surprised that the line

again = k.next();

still gets executed even when the user gets the color correct. I suggest you change the else code to the following:

if  (color.equalsIgnoreCase ("blue"))
      {    
        System.out.println ("You got the right color!");
        again = "No";
      }
    else
    {
        System.out.println ("That is not the right color. Would you like to try again? Yes/No"); 
        again = k.next();
    }

That will automatically tell the program not to run again if the user guesses correctly and will only read the user's answer for trying again if they answer incorrectly.

Bill W
  • 1,428
  • 1
  • 20
  • 29