The do loop

A common use of a do loop is to repeat an input until a valid response is entered. Here, the loop continues unit the user enters a valid month, a number from 1 to 12. When a valid month is enterd, the loop ends and the season is printed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//Get month with do loop until valid, switch/case to print season
//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="";
    do {
      System.out.print("Enter the number of the month:");
      month=keyboard.nextInt();
    } while(month<1 || month>12);
    switch (month) {
      case 3: case 4: case 5: season="Spring"; break;
      case 6: case 7: case 8: season="Summer"; break;
      case 9: case 10: case 11: season="Fall"; break;
      case 12: case 1: case 2: season="Winter"; break;
      //no default needed because do loop forces a valid month
    } //switch month
    System.out.println(season);
  }//main
}//class
CODE

Sample output:

Enter the number of the month:-3
Enter the number of the month:14
Enter the number of the month:10
Fall

NEXT: Functions