我正在制作一个程序,读取月份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);
}
}
}