0

I am trying to create a menu-driven application that uses If-Else statement. Unfortunately, it always results in the Else or Exit message. What's wrong with my code? Thank you!

package com.company;
import java.util.*;
public class Main {

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);

        System.out.print("""
                Good day!
                                        
                Get to now Java programming language!
                Please enter the letter that corresponds to your choice.
                A. What is Java language
                B. How to display a message
                C. How to get users' input
                E. Exit the program
                                        
                Choice: """);
        String choice = console.nextLine();

        while (true) {
            if (choice == "A") {
                String WhatIs = "Java is a Object-Oriented Programming Language \n";
                System.out.println(WhatIs);

            } else if (choice == "B") {
                String display = "Just use System.out.println \n";
                System.out.println(display);

            } else if (choice == "C") {
                String GetUser = "Import the package and use the Scanner method \n";
                System.out.println(GetUser);

            } else {
                String Exit = "Thank you for using this application.";
                System.out.println(Exit);
                break;
            }
        }
    }
}
  • Also, you should get new input _inside_ your loop, otherwise `choice` will never change and you loop indefinitely once you input "A", "B", or "C". Also also, you should stick to Java Naming Conventions. In your case, your variable names should start lowercase. – maloomeister Feb 15 '21 at 06:39
  • Hi! it worked, thank you so much! :D – Patricia Angelli Valderrama Feb 15 '21 at 21:07

1 Answers1

0

As the answer that @maloomeister mentioned in the comment:

Strings need to be compared via equals. So change choice == "A" etc., to choice.equals("A").

The detailed explanation is provided in this answer.

suntoch
  • 1,834
  • 2
  • 13
  • 13