Home > Blockchain >  Something missing or additional in my Do While loop, how do i fix it
Something missing or additional in my Do While loop, how do i fix it

Time:02-11

            String message = "Hello "   name   ", Do you know what day it is today?";
            answer = JOptionPane.showConfirmDialog(frame, message);
            JOptionPane.showMessageDialog(null, "Come on think a little harder", "Are you new here?",
                    JOptionPane.INFORMATION_MESSAGE);

        } while (answer == JOptionPane.NO_OPTION);

        if (answer == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null, "Great!", "Yay", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

When i press No, it will say "come on think a little harder" and loop back to 'do you know what day it is' but when i press yes, it still says 'come on think a little harder" and then only says "great'

What i want it to say when i press yes is only 'great'

I think i may have misplaced something that should not/should be in the while loop im not really sure..

CodePudding user response:

You're showing the no message before the determination has been made that it is a no message:

 while (true) {
        String message = "Hello "   name   ", Do you know what day it is today?";
        int answer = JOptionPane.showConfirmDialog(null, message);
        if (answer == JOptionPane.NO_OPTION) {
            JOptionPane.showMessageDialog(null, "Come on think a little harder", "Are you new here?", JOptionPane.INFORMATION_MESSAGE);
        } else if (answer == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null, "Great!", "Yay", JOptionPane.INFORMATION_MESSAGE);
            break;
        } else {
            break;
        }
    }

CodePudding user response:

You just have to add an if condition , otherwise Come on think a little harder will be exectued for both yes and no options.

do {
  String message = "Hello "   name   ", Do you know what day it is today?";
  answer = JOptionPane.showConfirmDialog(frame, message);

  if (answer == JOptionPane.NO_OPTION) { // Add if condition
    JOptionPane.showMessageDialog(null, "Come on think a little harder", "Are you new here?",
      JOptionPane.INFORMATION_MESSAGE);
  }

} while (answer == JOptionPane.NO_OPTION);

if (answer == JOptionPane.YES_OPTION) {
  JOptionPane.showMessageDialog(null, "Great!", "Yay", JOptionPane.INFORMATION_MESSAGE);
}
  •  Tags:  
  • java
  • Related