1

I have a problem with the code. This is the process -

  • First you enter your name
  • Then you enter your age
  • Then you enter your password (default value is "anybody")

Name and age can be entered without problem but the program evaluates the password with error. When you enter your password correctly, it still returns as false.

Please Help me!! Thanks.

    import java.util.Scanner;

    public class MyClass {

    public static void main(String[] args) {
        String name;
        int age;
        boolean trueOrFalse;
        boolean trueOrFalse2;

        String builtInPassword = "anybody";

        Scanner keyBoardInput = new Scanner(System.in);

            System.out.print("Please enter your First name: ");
            name = keyBoardInput.next();
            System.out.print("Please enter your age: ");
            age = keyBoardInput.nextInt();
            trueOrFalse = false;
            trueOrFalse2 = true;
            System.out.print("Please enter your Password: ");
        if (keyBoardInput.next() == builtInPassword) {
            System.out.println(trueOrFalse2);
        } else {
            System.out.println(trueOrFalse);
        } 

    }
}
display name
  • 4,165
  • 2
  • 27
  • 52
aghdaeea
  • 13
  • 3

3 Answers3

3

When comparing two strings in Java you'd want to use the .equals() method. This will compare the values of two strings, whereas == will compare reference.

String test = "test";
if(test.equals("test")) {
    //Do something
}
Evan Fajardo
  • 104
  • 9
  • Thank you.please enter these codes in some software like eclipse. after this change compiler don't let enter password and show false answer! – aghdaeea Jun 19 '15 at 21:54
  • if (keyBoardInput.equals(builtInPassword)) { System.out.println(trueOrFalse2); } – aghdaeea Jun 19 '15 at 22:02
0

You need to use .equals() on the string like this:

public static void main(String[] args) {
    String name;
    int age;
    boolean trueOrFalse;
    boolean trueOrFalse2;

    String builtInPassword = "anybody";

    Scanner keyBoardInput = new Scanner(System.in);

        System.out.print("Please enter your First name: ");
        name = keyBoardInput.next();
        System.out.print("Please enter your age: ");
        age = keyBoardInput.nextInt();
        trueOrFalse = false;
        trueOrFalse2 = true;
        System.out.print("Please enter your Password: ");
    if (keyBoardInput.next().equals(builtInPassword)) {
        System.out.println(trueOrFalse2);
    } else {
        System.out.println(trueOrFalse);
    } 
}
bhspencer
  • 13,086
  • 5
  • 35
  • 44
0

Thank you solved my problem. I found another way :

if (keyBoardInput.hasnext(builtInPassword)) {
    System.out.println(trueOrFalse2);
} else {
    System.out.println(trueOrfalse)
 }
aghdaeea
  • 13
  • 3