The following algorithm yields the seasons (Spring, Summer, Fall or Winter) for
ID: 3676821 • Letter: T
Question
The following algorithm yields the seasons (Spring, Summer, Fall or Winter) for a given month and the day.
If month is 1, 2 or 3, season = “Winter”
Else if month is 4, 5 or 6, season = “Spring”
Else if month is 7, 8, or 9, season = “Summer”
Else if month is 10, 11, or 12, season = “Fall”
If month is divisible by 3 and day is greater than or equal to 21
If season is winter, season equals “spring”
Else if season is spring, season equal “summer”
Else if season is summer, season equals “fall”
Else season equals winter
Write a program that prompts the user for a month and day and then prints the season, as determined by this algorithm.
Program must be written in Java
Explanation / Answer
package assignment;
import java.util.Scanner;
public class Seasons {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter month(1 to 12):");
int month = sc.nextInt();
while(month <0 || month >12) {
System.out.println("Enter valid month b/w 1 to 12:");
month = sc.nextInt();
}
System.out.println("Enter day(1 to 30):");
int day = sc.nextInt();
while(day <0 || day >30) {
System.out.println("Enter valid day(1 to 30):");
day = sc.nextInt();
}
//As per algorithm
String season = "";
//If month is 1, 2 or 3, season = “Winter”
if(month >= 1 && month <=3)
season = "Winter";
//Else if month is 4, 5 or 6, season = “Spring”
else if(month >= 4 && month <=6)
season = "Spring";
//Else if month is 7, 8, or 9, season = “Summer”
else if(month >= 7 && month <=9)
season = "Summer";
// Else if month is 10, 11, or 12, season = “Fall”
else if(month >= 10 && month <=12)
season = "Fall";
// If month is divisible by 3 and day is greater than or equal to 21
if(month % 3 == 0 && day >=21) {
if("Winter".equalsIgnoreCase(season))
// If season is winter, season equals “spring”
season = "Spring";
// Else if season is spring, season equal “summer”
else if("Winter".equalsIgnoreCase(season))
season = "Summer";
// Else if season is summer, season equals “fall”
else if("Summer".equalsIgnoreCase(season))
season = "Fall";
// Else season equals winter
else
season = "Winter";
}
System.out.println(" Season: "+season);
}
}
--------------output-----------------------
Enter month(1 to 12):
3
Enter day(1 to 30):
2
Season: Winter
Enter month(1 to 12):
3
Enter day(1 to 30):
24
Season: Spring
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.