我正在编写一个代码,它接受用户输入的年份和月份,并根据给定月份打印出特定月份的日历。它使用循环使打印成为可能。
这是所需的输出
Enter a year: 2013
Enter a month (1-12): 2
February 2013
----------------------------------------
sun mon tue wed thrus fri sat
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28
我在网上查看有关如何打印整个日历(1 月至 12 月全年)的代码的事情,但我想知道是否有办法将整个打印输出缩短到用户选定的月份。我确实将这个问题视为参考,并发现它非常有帮助,但答案全年都打印出来。 How to display calendar in java
我认为应该对程序进行更改的是,在几个月内应该有 for 循环和确定年份是否为闰年的部分代码。我认为应该有一个用于选择月份的数组,无论哪个都将打印在该部分的中间。
答案 0 :(得分:1)
运行它并告诉我它是否符合您的要求:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the year: ");
int Y = sc.nextInt(); // year
System.out.println();
System.out.print("Enter the weekday the year starts on (1 for Sunday, 2 for Monday, 2 for Tuesday, etc:) ");
int startDayOfMonth = sc.nextInt();
int spaces = startDayOfMonth-1;
System.out.println();
// startDayOfMonth
// months[i] = name of month i
String[] months = { "", // leave empty so that we start with months[1] = "January"
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December" };
// days[i] = number of days in month i
int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.print("Enter the month you wish to display (1 for January, 2 for February, etc) ");
int M = sc.nextInt();
System.out.println();
// check for leap year
if ((((Y % 4 == 0) && (Y % 100 != 0)) || (Y % 400 == 0)) && M == 2)
days[M] = 29;
// print calendar header
// Display the month and year
System.out.println(" " + months[M] + " " + Y);
// Display the lines
System.out.println("_____________________________________");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
// spaces required
spaces = (days[M - 1] + spaces) % 7;
// print the calendar
for (int i = 0; i < spaces; i++)
System.out.print(" ");
for (int i = 1; i <= days[M]; i++) {
System.out.printf(" %3d ", i);
if (((i + spaces) % 7 == 0) || (i == days[M]))
System.out.println();
}
System.out.println();
}
}
我从您引用的帖子中编辑了答案,以使用选择特定月份而不是所有月份的扫描仪