if / else statements

We want to test if a number is a valid month. In the first example, we test if the month is valid, using && (and). The number is a valid month if it is greater than or equal to 1 AND it is less than of equal to 12.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Input a valid month
package month;
import java.util.*;
public class ValidMonth {
	public static void main(String[] args) {
		Scanner keyboard=new Scanner(System.in); //do just once
		int month;
		System.out.print("Enter the number of a month:");
		month=keyboard.nextInt();
		if (month >=1 && month <=12)
		  System.out.println(month+" is a valid month");
		else 
		  System.out.println(month+" is NOT a valid month");
	}//main
}//class
CODE

In the second example we test if the month is invalid using || (or). A month is invalid if it is less than 1 OR greater than 12.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Input a valid month
package month;
import java.util.*;
public class ValidMonth {
	public static void main(String[] args) {
		Scanner keyboard=new Scanner(System.in); //do just once
		int month;
		System.out.print("Enter the number of a month:");
		month=keyboard.nextInt();
		 if (month <1 || month >12)
		  System.out.println(month+" is NOT a valid month");
		else 
		  System.out.println(month+" is a valid month");
	}//main
}//class
CODE

NEXT: