请使用JAVA语言编写以下要求的代码:IO练习:从键盘上输入任意年份和月份,输出该月份的日历,并输出到文件中。
时间: 2024-03-11 07:50:40 浏览: 55
java代码-使用java从键盘输入月份,输出这个月的天数,比如输入是1,则输出31天的源代码
5星 · 资源好评率100%
以下是使用Java语言编写的代码,可实现从键盘上输入任意年份和月份,输出该月份的日历,并输出到文件中:
```java
import java.util.Scanner;
import java.io.*;
public class CalendarIO {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("请输入年份:");
int year = input.nextInt();
System.out.print("请输入月份:");
int month = input.nextInt();
// 计算该月份的天数
int days = getDays(year, month);
// 计算该月份的第一天是星期几
int firstDayOfWeek = getFirstDayOfWeek(year, month);
// 输出日历并写入文件
String calendar = getCalendar(year, month, days, firstDayOfWeek);
System.out.println(calendar);
File file = new File("calendar.txt");
FileWriter writer = new FileWriter(file);
writer.write(calendar);
writer.close();
}
/**
* 计算指定年份和月份的天数
*/
public static int getDays(int year, int month) {
int days = 0;
if (month == 2) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
} else {
days = 31;
}
return days;
}
/**
* 计算指定年份和月份的第一天是星期几
*/
public static int getFirstDayOfWeek(int year, int month) {
int days = 0;
for (int i = 1900; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
days += 366;
} else {
days += 365;
}
}
for (int i = 1; i < month; i++) {
days += getDays(year, i);
}
int dayOfWeek = (days + 1) % 7;
return dayOfWeek;
}
/**
* 获取指定年份和月份的日历
*/
public static String getCalendar(int year, int month, int days, int firstDayOfWeek) {
StringBuilder builder = new StringBuilder();
// 输出年份和月份
String monthName = getMonthName(month);
builder.append("\t\t" + year + "年" + monthName + "月\n");
// 输出星期几
builder.append("日\t一\t二\t三\t四\t五\t六\n");
// 输出第一行日期
for (int i = 0; i < firstDayOfWeek; i++) {
builder.append("\t");
}
for (int i = 1; i <= 7 - firstDayOfWeek; i++) {
builder.append(i + "\t");
}
builder.append("\n");
// 输出其它行日期
int count = 7 - firstDayOfWeek + 1;
while (count <= days) {
for (int i = 0; i < 7; i++) {
if (count <= days) {
builder.append(count + "\t");
count++;
} else {
builder.append("\t");
}
}
builder.append("\n");
}
return builder.toString();
}
/**
* 获取月份的名称
*/
public static String getMonthName(int month) {
String[] monthNames = {"", "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
return monthNames[month];
}
}
```
使用说明:
- 在命令行窗口中,输入 `javac CalendarIO.java` 编译程序;
- 输入 `java CalendarIO` 运行程序;
- 按照提示,在命令行窗口中输入任意年份和月份,即可输出该月份的日历,并将其写入文件 `calendar.txt` 中。
阅读全文