-2

I have an if statement that is supposed to compare the return value of a method, which I've set as a string, to determine which method to call next. However, the method doesn't seem to be returning the correct value, because the program never enters the if-statements. I've already tested it by assigning a value straight to the variable, without using the method, and it works the way it's supposed to from that point on.

Here is the method that is giving me trouble:

public String loadMenu();
{
    Scanner input = new Scanner(System.in);
    System.out.print('\u000C');
    System.out.println("**********************************************************************" + "\n" +
                       "|                  Welcome to Custom Password Maker                  |" + "\n" +
                       "**********************************************************************" + "\n" +
                                                                                                  "\n" +
                       "Please type in which option below you would like to choose"             + "\n" + "\n" +
                       "1) MAKE A PASSWORD"                                                     + "\n" +
                       "2) EXIT PROGRAM"                                                                );
    return input.nextLine();
}

And Here is the part where I try to use the return value in an if statement:

public static void main(String[] args)
{
    Menus menu = new Menus();
    String choice = menu.loadMenu();
    System.out.println(choice);
    //choice = "1";
    if (choice == "1")
    {
        menu.makePassword();
    }
    if (choice == "2")
    {
        menu.exitProgram();
    }
    else
    {
        System.out.println("Huh...");
    }
}

I would expect the variable 'choice' to equal "1" when the user inputs the number 1, and when I use System.out.println it prints the number 1 in the terminal, but it doesn't satisfy the if statement.

1 Answers1

1

Use .equals() to compare your strings, meaning comparing choice and "1".

Like this

if(choice.equals("1"))
hiew1
  • 1,394
  • 2
  • 15
  • 23