0

I'm new to JAVA programming and right now I'm facing a strange case. I set the confirmation variable to the type of String , it will hold the user input. When the user type "yes" The program should create a new user, but it didn't . Instead, it rise the false alarm "Process is canceled by user". It seems the convirmation variable didn't evaluated correctly. Any advice guys. thanks.

This is my code (it's pretty simple though):

import java.util.Scanner;

public class CreateUser {
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        String firstName;
        String lastName;
        String confirmation;

        System.out.println("Create new user");
        System.out.print("Enter first name : ");
        firstName = input.nextLine();
        System.out.print("Enter last name : ");
        lastName = input.nextLine();

        System.out.println("Are you sure?");
        confirmation = input.nextLine();

        System.out.println(confirmation); // this line is to make sure that the variable value is "yes"

        if(confirmation == "yes")
        {
            Users newUser = new Users(firstName, lastName);
            System.out.printf("User %s %s has been created\n", firstName, lastName);
            System.out.println("Total active users now is :"+Users.getRegisteredUsers());
        }
        else
        {
            System.out.println("Process is canceled by user");
        }

        input.close();

    }
}

And this is the output :

Create new user
Enter first name : fin
Enter last name : fin
Are you sure?
yes
yes
Process is canceled by user
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
under5hell
  • 997
  • 3
  • 16
  • 40

1 Answers1

2

Use

if (confirmation.equals("yes")) {
}

instead of

if(confirmation == "yes")

.equals() compares the values of 2 strings. == compares the memory reference to see if they point to the same object. Reference article

DT7
  • 1,615
  • 14
  • 26
  • you should explain why so the OP learns, not just post the answer. – SnakeDoc Nov 05 '13 at 15:58
  • 1
    Or "yes".equals(confirmation) to avoid NPE – user2336315 Nov 05 '13 at 15:58
  • This is solve my problem. But, why we cannot use "==" for this case. I made a simple program to test the "==". I made String a = "yes" then evaluate it using : if(a == "yes")? System.out.println("OK") : System.out.println("not OK"); and it evaluated correctly. Why did it fail with my confirmation variable? would you explain it? thanks – under5hell Nov 05 '13 at 16:00
  • 1
    `.equals()` compares the values of 2 strings. `==` compares the memory reference to see if they point to the same object. – DT7 Nov 05 '13 at 16:04
  • hmm.. it's still lil' bit confusing for me... :) But thanks for your solution. – under5hell Nov 05 '13 at 16:12