我目前正在做一个问题集,我必须创建一个日历来显示一年中的所有月份,包括其中的月份的日期。但是,我遇到了每月第一行的间隔问题。在课堂上,我们只了解到switch语句,如果,否则,同时,做,而对于循环如何在java中显示日历
这里是目前显示的我的一个月份:
Image of output 在图片中是不显示我的输入,但我写的是2016年的年份和5年的平均年份开始英寸
Image of output of what what is desired 再次,一个什么是想要的图片。我认为我的问题可能是我使用的公式:int firstDayEachMonth =(daysMonth + firstDayYear)%7;尽管老师给了我们这个等式来使用,但它似乎不起作用。
正如你所看到的,第一行的空格是左侧的,它应该与指定日期对齐,在这种情况下,对于1月份,1月1日应该在星期五和1月2日对齐,并与星期六保持一致但目前在星期日和星期一。
import java.util.Scanner;
public class DisplayCalendar
{
public static void main(String[] args)
{
//Create a new scanner
Scanner input = new Scanner(System.in);
// Prompt user to enter year
System.out.print("Enter a year: ");
int year = input.nextInt();
// Prompt user to enter first day of the year
System.out.print("Enter the weekday that the year starts: ");
int firstDayYear = input.nextInt();
// A for loop that prints out each month
for(int month = 1; month <= 12; month++)
{
// Set the value of the amount of days in a month
int daysMonth = 0;
// Set value of the month
String monthDisplay = "";
// Find name of each month and number of days
switch(month)
{
case 1: monthDisplay = "January";
daysMonth = 31;
break;
case 2:
monthDisplay = "February";
int leapYear = 0;
while (leapYear > -1)
{
// Count all years that are divisible by 4 to be a leap year.
leapYear += 4;
// If the year inputted is a leap year, the days of the month will be 29.
if (year == leapYear)
{
daysMonth = 29;
break;
}
else
{
daysMonth = 28;
}
}
break;
case 3: monthDisplay = "March";
daysMonth = 31;
break;
case 4: monthDisplay = "April";
daysMonth = 30;
break;
case 5: monthDisplay = "May";
daysMonth = 31;
break;
case 6: monthDisplay = "June";
daysMonth = 30;
break;
case 7: monthDisplay = "July";
daysMonth = 31;
break;
case 8: monthDisplay = "August";
daysMonth = 31;
break;
case 9: monthDisplay = "September";
daysMonth = 30;
break;
case 10: monthDisplay = "October";
daysMonth = 31;
break;
case 11: monthDisplay = "November";
daysMonth = 30;
break;
case 12: monthDisplay = "December";
daysMonth = 31;
break;
// If the month is not recognized, dialog box will be displayed, and then exits program.
default : System.out.print("Invalid: Your month is not recognized. ");
System.exit(0);
}
// Display the month and year
System.out.println(" "+ monthDisplay + " " + year);
// Display the lines
System.out.println("_____________________________________");
// Display the days of the week
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
// Print spaces depending on the day the month starts.
int firstDayEachMonth = (daysMonth + firstDayYear)%7;
for (int space = 1; space <= firstDayEachMonth; space++)
System.out.print(" ");
// Print the days
for (int daysDisplay = 1; daysDisplay <= daysMonth; daysDisplay++)
{
if (firstDayYear%7 == 0)
System.out.println();
System.out.printf("%3d ", daysDisplay);
firstDayYear += 1;
}
System.out.println();
}
}
}
假设这是功课,你不准看标准的Java库和API?如果你是,java.util.Calendar和java.lang.String.format可能是有趣的。特别是,Calendar.roll将帮助你完成一大堆工作... –
嘿,我们不能使用不同的库,只能保持扫描仪。 – Flinze