if / else statements

In this example, we print the month based on the month. Notice that we must use nested elses in order for the last else to work. If there were just one else, it would print out invalid if it wasn't fall.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Input a month, print the season
package months;
import java.util.*;
public class Seasons {
	public static void main(String[] args) {
		Scanner keyboard=new Scanner(System.in); //do just once
		int month;
		String season="";
		System.out.print("Enter the number of a month:");
		month=keyboard.nextInt();
		if (month==1 || month==2 || month==12) 
			System.out.println("Winter");
		else if (month==3 || month==4 || month==5)
			System.out.println("Spring");
		else if (month==6 || month==7 || month==8)
			System.out.println("Summer");
		else if (month==9 || month==10 || month==11)
			System.out.println("Fall");
		else 
			System.out.println(month+" is not a valid month");
	}//main
}//class
CODE

Sample output:

Enter the number of a month:3
Spring

Enter the number of a month:0
0 is not a valid month

NEXT: switch: looking at one variable