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

While loop java question.

Alright, so basically I just set out to practice working with loops, bc it's something I need to work on before moving on as I don't have a firm confident understanding of them yet. I wanted to write out simple code using the while to check to see if the user input was correct. I was finally able to get this task done, but I found one issue and I think I know what it is now. Heres the code so you can see whats going on here...

import java.io.Console;

public class questionloop {

public static void main(String[] args) {
Console console = System.console();

String name = console.readLine("What is your name? ");

while (name != ("Mike")) {
    name = console.readLine("What is your name? ");
    if (name.equalsIgnoreCase("Mike")){
        break;
    }
    }
    console.printf("Welcome, lets continue...");
}

}

............. So, I started of using the != condition so that if the user entered a wrong username it would prompt them over and over again until they reached the right name.. So, fine. I run this type in a wrong name, i'm prompted with a line to ask me once again for my username, when I type in Mike, the correct name.. it goes on to "Welcome, lets continue.."

Great! but, when further testing I found that if I type Mike in the first time, it goes on to prompt me again asking for my username again although I already defined that as the correct answer. Why is this?

I guess in this situation it would be better to use a do while loop? Instead of a while loop?

meant do while loop in that last sentence.

1 Answer

First off, when you compare strings you should use .equals() or .equalsIgnoreCase(). Not sure the exact reason, but it can cause issues. Something like this:

while (!(name.equalsIgnoreCase("Mike"))

Second off you prompt the user for their name twice, once in the loop and once before the loop. Just don't initialize it when you create the variable.

String name;

while (!(name.equalsIgnoreCase("Mike")) {
  name = console.readLine("What is your name? ");
}

You also dont need to check to see if the name variable equals "Mike" inside the loop, because the loop does that for you. So just remove this:

if (name.equalsIgnoreCase("Mike")){
  break;
}