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 trialShaun Kelly
5,648 PointsI am trying to create a small code that asks for a password and then once it's correct. It says "Correct".
If it's not correct then have it say "Incorrect". This is my code
String password = console.readLine("Enter Password: \n");
String answer = "Hello";
if (password == answer) {
console.printf("Correct");
}
else {
console.printf("Incorrect!");
}
1 Answer
Ken Alger
Treehouse TeacherShaun;
I would try something like:
import java.io.Console;
public class password {
public static void main(String[] args) {
Console console = System.console();
String password = console.readLine("Enter Password: ");
String answer = "Hello";
if (password.equals(answer)) {
console.printf("Correct. \n");
System.exit(0);
} else {
console.printf("Sorry, incorrect. \n");
System.exit(0);
}
}
}
Remember that in Java ==
tests for reference equality, where .equals()
tests for value equality. Consequently, if you actually want to test whether two strings have the same value you should use .equals()
(except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning). ==
is for testing whether two strings are the same object.
Hope it helps and happy coding,
Ken