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
Jillian Skinner
1,715 Pointsdo/while looping issues...want to end the "do" loop early.
See the program below.
Works great until I enter the correct password. Then it prints "Incorrect. Try again. That's correct. Access granted". When I enter the correct password, I want to skip "Incorrect. Try again", and jump to "That's correct. Access granted".
Can't figure it out! :-( Thanks in advance!
Here's my code:
```import java.util.Scanner;
public class TestSimpleWhileStatements {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String password = "Nirvana";
String userInput;
do {
System.out.println("Type your password now.");
userInput = keyboard.next();
System.out.println("Incorrect. Try again.");
}
while (!userInput.equalsIgnoreCase(password));
System.out.println("That's correct. Access granted.");
keyboard.close();
}
}
3 Answers
John Keith Zank
11,848 PointsYou can do it with just an if statement.
if(userInput.equalsIgnoreCase != password)
{
System.out.println("Incorrect. Try Again.");
}
It's been a while since I've used java but that should do what you're looking for.
Jillian Skinner
1,715 PointsThat does work, but I need for it to be a loop though, so if the incorrect password continues to be input, then the program keeps asking for the password. :-( Thanks though!
John Keith Zank
11,848 PointsI'm sorry, I mean to say that you nest the if statement within the do while loop. Here's the full code for an example.
import java.util.Scanner;
public class TestSimpleWhileStatements {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String password = "Nirvana";
String userInput;
do {
System.out.println("Type your password now.");
userInput = keyboard.next();
if(!userInput.equalsIgnoreCase(password))
{
System.out.println("Incorrect. Try Again.");
}
}
while (!userInput.equalsIgnoreCase(password));
System.out.println("That's correct. Access granted.");
keyboard.close();
}
It will enter the if statement and print "Incorrect. Try Again." only if the password is incorrect, otherwise it goes to the end of the loop and exits.
Jillian Skinner
1,715 PointsThank you!!!