0

Whenever the user input is 1 or Jan, the code does not read and jump to second statement and display

Invalid month has been entered

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a month:  ");

        String month=in.nextLine();


        if((month == "1") || (month == "Jan")){

            System.out.println("Month: January");
        }
        else{
            System.out.println("Invalid month has been entered");
Key
  • 37
  • 1
  • 8

1 Answers1

5

With Strings, use "equals" instead of ==.

if(("1".equals(month)) || ("Jan".equals(month)))

This is needed because Strings are not primitive types, but a special kind of Objects in Java.

You can check the following for more info: What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
javatutorial
  • 1,916
  • 15
  • 20