0

I have made a program to tell what season it is based on the month. However, no matter what i input, it says that it is Fall. Here is the code:

import java.util.Scanner;
public class SeasonChecker {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);

    System.out.println("What month is it??");
    String month = input.nextLine();
    System.out.println(month);
    if (month == "december"||month == "January"||month=="February"){
        System.out.println("Then it is Winter?");
    }
    else if (month=="March"||month=="May"||month=="April"){
        System.out.println("Then it is Spring!!!");

    }
    else if (month=="June"||month=="July"||month=="August"){
        System.out.println("Then it is Summer!");

    }
    else {

        System.out.println("Then it is Autumn!");

    }
    input.close();
}

}

HAL 9000
  • 61
  • 1
  • 6
  • 3
    Don't compare string values with `==`; that compares object references to determine if they're the same object. Use `equals` to compare string values. – rgettman Jul 01 '13 at 18:30

3 Answers3

5
month == "december"||month == "January"

use equals() method while comparing Strings.

Example:

   "december".equals(month) || "January".equals(month)

== checks for reference equality (both references pointing to same object are not). equals() checks for content of the object.

kosa
  • 65,990
  • 13
  • 130
  • 167
3

In Java, with strings, you should use the equals method to make comparison, not the literal == comparison. So month.equals("January") Using == will compare the memory references and see if they are the same reference for objects. == is meant for comparing literals like int or double

mistahenry
  • 8,554
  • 3
  • 27
  • 38
2

use equals method instead of ==

if (month.equals("december")||month.equals("January")||month.equals("February")){

in java == compares the reference. But equals method compares the value of String.

stinepike
  • 54,068
  • 14
  • 92
  • 112