Conditional operator: ?

This example reads in the number of a month and stores if it is valid or not in a variable.

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

Sample output:

Enter the number of a month:0
not valid

Enter the number of a month:6
valid

NEXT: