Issues with IF else Statement
Hi All,
I'm not sure whats wrong with the following code. I skips to final else and prints the message, but doesn't validate the if conditions.
Code java:
import java.util.Scanner;
public class Ifprograms {
public static void main(String[] args)
{
String Mon;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Month you wish to determine the season : ");
Mon = sc.next();
// System.out.println("Mon is " +Mon);
String season;
if(Mon == "December"||Mon == "January"||Mon == "February")
season = "Winter";
else if(Mon == "March" || Mon == "April" || Mon == "May")
season = "Spring";
else if(Mon == "July" || Mon == "August" || Mon == "June")
season = "Summer";
else if(Mon == "September" || Mon == "October" || Mon == "November")
season = "Autumn";
else
season = "Invalid Month";
System.out.println(Mon+" is in the " +season+ ".");
}
}
Re: Issues with IF else Statement
Don't use == with Strings, or any Objects, unless you want to test whether they are the same instance. Use the equals() method instead. Do a search on google or these forums for a better explanation of why.
Re: Issues with IF else Statement
Thank You Kevin!!!
That worked!! below is the code!
import java.util.Scanner;
Code java:
public class Ifprograms {
public static void main(String[] args)
{
String Mon;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Month you wish to determine the season : ");
Mon = sc.next();
System.out.println("Mon is " +Mon);
String season;
if (Mon.equals("December")||Mon.equals("January")||Mon.equals("February"))
season = "Winter";
else if(Mon.equals("March")||Mon.equals("April")||Mon.equals("May"))
season = "Spring";
else if(Mon.equals("June")||Mon.equals("July")||Mon.equals("August"))
season = "Summer";
else if(Mon.equals("September")||Mon.equals("October")||Mon.equals("November"))
season = "Autumn";
//System.out.println(Mon+"is in the " +season+ ".")
else
season = "Invalid Month";
System.out.println(Mon+" is in the " +season+ ".");
}
}