Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Do while loop only executes once? Simple password program

I am trying to just practice some basic Java but this do while loop only goes once. This program is pretty basic and not useful at all I'm just testing out the do while loop pretty much. I'm very new to java sorry if the code looks bad.

import java.io.Console;
public class quiz {
        public static void main(String[] args) {
Console console = System.console();
console.printf("\033[H\033[2J");
String info = console.readLine("Enter your secret information: ");
console.printf("\033[H\033[2J");
String password;
String passwordAttempt;
boolean correctPassword == false;
do {

password = console.readLine("Enter a password:  ");
console.printf("\033[H\033[2J");
passwordAttempt = console.readLine("If you would like to access this information please enter the password:\n");

correctPassword = (passwordAttempt.equals(password));

if (passwordAttempt.equals(password)) {
console.printf("\n%s", info);
}else {
console.printf("Incorrect password! Please retry: \n");
}
}
while (correctPassword);
}
}

2 Answers

Steven Parker
Steven Parker
243,656 Points

It would execute only once if your entry was wrong, it would loop again if correct.

This is probably the opposite of the behavior you'd really like to have. You can invert the test to get it the other way:

while (!correctPassword);

I think I understand what you're saying. I tried to replace the last while (correctPassword); with what you said, but it still only executes once when the password is incorrect. Was that the only correction that I had to do in order to fix it? Thank you