0

Hi I have some code for the Java console to do something when specific keys are pressed. The system inputs and stores the key as a string no bother and I can print it out to confirm it works. However the code never enters the conditional statement and instead jumps to the else every time. Here is the code:

Scanner MenuChoice = new Scanner(System.in);
    Products.MenuCode = MenuChoice.next();


                if(Products.MenuCode=="F")
                {
                //Run subprogram for finding a product.
                Find.main();    

                }

                else{
                System.out.println("F - Find a Product");
                 System.out.println("p - Purchase a Product");
                  System.out.println("Q - Quit");
                  Scanner MenuChoice2 = new Scanner(System.in);
                  Products.MenuCode = MenuChoice2.next();
                };

What's going wrong?

2 Answers 2

3

you can do this

Scanner MenuChoice = new Scanner(System.in);
Products.MenuCode = MenuChoice.next();


            if(Products.MenuCode.equals("F")) // use equals method 
            {
            //Run subprogram for finding a product.
            Find.main();    

            }

            else{
            System.out.println("F - Find a Product");
             System.out.println("p - Purchase a Product");
              System.out.println("Q - Quit");
              Scanner MenuChoice2 = new Scanner(System.in);
              Products.MenuCode = MenuChoice2.next();
            };
Sign up to request clarification or add additional context in comments.

Comments

0

you can't compare Strings using == you have to use the equals methode.

The equals method works like this:

boolean b = string1.equals(string2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.