我正在制作一个程序,该程序在 1-12 月和开始日读取,1-7 表示星期日、星期一等。它打印第一周很好,但我在打印第一周后的其余几天时遇到问题。它不会将输出格式化为在其余天之间留有空格,仅在第一周后的第一天。
旁注:键盘是我的项目中包含的一个类
这是我的代码:
import java.io.*;
public class CalendarMonth
{
static final int WEEK = 7;
public static void main(String[] args) throws IOException
{
String proceed;
char repeatCheck;
int days;
String leapYear;
char leapYearCheck;
int startDay;
do
{
days = getDays();
System.out.println(days);
System.out.println("Please enter a number 1-7 that the month starts on: (1 for sunday, 2 for monday, etc)");
startDay = Keyboard.readInt();
while(startDay < 1 || startDay > 7)
{
System.out.println("You did not enter a number 1-7, Try again: ");
startDay = Keyboard.readInt();
}
System.out.println(" s m t w th f sa");
printMonth(days,startDay);
System.out.println("\nWould you like to print another month?");
proceed = Keyboard.readString();
repeatCheck = proceed.charAt(0);
}while(repeatCheck == 'y');
}
public static int getDays() throws IOException
{
int month;
String leapYear;
int startDay;
int days = 0;
char leapYearCheck;
System.out.println("Please input a number 1-12 to print the corresponding month: ");
month = Keyboard.readInt();
while (month < 1 || month > 12)
{
System.out.println("You did not put a number 1-12, Try again: ");
month = Keyboard.readInt();
}
switch(month)
{
case 1: days = 31;
break;
case 2:
System.out.println("is it a leap year? ");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
while(leapYearCheck != 'y' && leapYearCheck != 'n')
{
System.out.println("you did not enter a yes or no answer, is it a leap year?");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
}
if (leapYearCheck == 'y')
{
days= 29;
}
else
{
days = 28;
}
break;
case 3: days = 31;
break;
case 4: days = 30;
break;
case 5: days = 31;
break;
case 6: days = 30;
break;
case 7: days = 31;
break;
case 8: days = 31;
break;
case 9: days = 30;
break;
case 10: days = 31;
break;
case 11: days = 30;
break;
case 12: days = 31;
break;
}
return days;
}
public static void printMonth(int days, int startDay)
{
int count;
count = startDay;
for (int counter = 1; counter <= 7; counter++)
{
if (counter < startDay)
{
System.out.print(" ");
count = count-1;
}
else
{
System.out.printf("%2d", count);
count++;
}
}
//int restOfTheMonth = (WEEK - startDay);
System.out.println();
for(int restOfTheMonth = count; restOfTheMonth <= days; restOfTheMonth++)
{
if (restOfTheMonth%WEEK==0)
{
System.out.println();
}
System.out.printf("%2d", restOfTheMonth);
}
}
}