**5.28(显示每月第一天是星期几)编写程序,提示用户输入年份和代表该年第一天是星期几的数字,然后在控制台上显示该年各个月份的第一天是星期几。例如,如果用户输入的年份是2013和代表2013年1月1日为星期二的2,程序应该显示如下输出:
January 1, 2013 is Tuesday
…
December 1, 2013 is Sunday
**5.28 (Display the first days of each month) Write a program that prompts the user to enter the year and first day of the year, then displays the first day of each month in the year. For example, if the user entered the year 2013, and 2 for Tuesday, January 1, 2013, your program should display the following output:
January 1, 2013 is Tuesday
…
December 1, 2013 is Sunday
下面是参考答案代码:
import java.util.*;
public class DisplayTheFirstDaysOfEachMonthQuestion28 {
public static void main(String[] args) {
int year, theFirstDay, totalDay = 0;
Scanner inputScanner = new Scanner(System.in);
System.out.print("Enter the year: ");
year = inputScanner.nextInt();
System.out.print("Enter the first day of the year: ");
theFirstDay = inputScanner.nextInt();
for (int i = 1; i <= 12; i++) {
switch (i) {
case 1:
System.out.print("January 1, " + year + " is ");
break;
case 2:
totalDay += 31;
System.out.print("February 1, " + year + " is ");
break;
case 3:
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
totalDay += 29;
else
totalDay += 28;
System.out.print("March 1," + year + " is ");
break;
case 4:
totalDay += 31;
System.out.print("April 1," + year + " is ");
break;
case 5:
totalDay += 30;
System.out.print("May 1, " + year + " is ");
break;
case 6:
totalDay += 31;
System.out.print("June 1, " + year + " is ");
break;
case 7:
totalDay += 30;
System.out.print("July 1, " + year + " is ");
break;
case 8:
totalDay += 31;
System.out.print("August 1, " + year + " is ");
break;
case 9:
totalDay += 31;
System.out.print("September 1, " + year + " is ");
break;
case 10:
totalDay += 30;
System.out.print("October 1, " + year + " is ");
break;
case 11:
totalDay += 31;
System.out.print("November 1, " + year + " is ");
break;
case 12:
totalDay += 30;
System.out.print("December 1, " + year + " is ");
}
int futureDay = (theFirstDay + totalDay) % 7;
switch (futureDay) {
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
}
}
inputScanner.close();
}
}
运行效果:
注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等