我是一名初学者,对Java有一些经验。
我做了这个简单的日历程序,并在过去的一周里不断地修改。我想这样做,当用户输入一个月和一年时,会出现一系列完美的日期。但是,我想更改它,这样用户只需要一年,并且显示了整组月份。
例如,代码要求输入年份:。用户必须选择他们想要的任何年份(我已经处理了闰年问题),从1月到12月的所有月份都必须以正确的顺序显示。我试图修改我的代码,但我一直搞砸。我如何才能以最好的方式更改代码,以便在用户给出的一年中获得整个月数?
import java.util.Scanner;
public class Month
{
private static final String[] MONTHS = {
"", "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
};
private static final int[] NUMDAYS = {
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
private int month;
private int year;
public Month(int month, int year) {
this.month = month;
this.year = year;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
private boolean isLeapYear() {
if(year % 400 == 0) {
return true;
}
if(year % 100 == 0) {
return false;
}
return year % 4 == 0;
}
private int getNumDays() {
if(month == 2) {
if(isLeapYear()) {
return 29;
}
else {
return 28;
}
}
else {
return NUMDAYS[month];
}
}
private int getStartDOW() {
int m, y;
if(month < 3) {
m = month + 12;
y = year - 1;
}
else {
m = month;
y = year;
}
return (13 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
}
public void printCalendar() {
//I changed this part so that the month and year could be centered, if you have an
//easier or cleaner way to do it, I would appreciate learning it.
if(month == 2||month == 11 || month == 12 || month == 9){
System.out.println(" " + MONTHS[month] + " " + year);
}else if(month == 3||month == 4 || month == 6 || month == 7 || month == 5){
System.out.println(" " + MONTHS[month] + " " + year);
}else if(month == 1||month == 10 || month == 8){
//This is what I originally had System.out.println(" " + MONTHS[month] + " "
//+ year);
}
System.out.println(" S M T W T F S");
int dow = getStartDOW();
for(int i = 0; i < dow; i++) {
System.out.print(" ");
}
int numdays = getNumDays();
for(int i = 1; i <= numdays; i++) {
System.out.printf("%2d ", i);
if(dow == 6) {
System.out.println();
dow = 0;
}
else {
dow++;
}
}
System.out.println();
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter month (1-12)");
int month = s.nextInt();
System.out.println("Enter year: ");
int year = s.nextInt();
Month m = new Month(month, year);
m.printCalendar();
}
}
1条答案
按热度按时间ocebsuys1#
因此,您有一个函数,它获取月份和年份,并渲染该月份。
您可以创建另一个仅以年份作为参数的函数,然后遍历所有月份并调用需要月份和年份作为参数。它还将渲染的月份组合为一年日历。