请帮我编程一份JAVA代码,并实现以下功能 IO练习:从键盘上输入任意年份和月份,输出该月份的日历,并输出到文件中。
时间: 2024-03-11 18:50:50 浏览: 72
好的,这是一份基于Java的代码实现你的要求:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class CalendarIO {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scanner.nextInt();
System.out.println("请输入月份:");
int month = scanner.nextInt();
scanner.close();
String[][] calendar = getCalendar(year, month);
printCalendar(calendar);
saveToFile(calendar, year, month);
}
private static String[][] getCalendar(int year, int month) {
LocalDate date = LocalDate.of(year, month, 1);
int lengthOfMonth = date.lengthOfMonth();
int dayOfWeek = date.getDayOfWeek().getValue();
String[][] calendar = new String[6][7];
int index = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
if (index <= lengthOfMonth && (i == 0 && j >= dayOfWeek - 1 || i > 0)) {
calendar[i][j] = String.valueOf(index++);
} else {
calendar[i][j] = "";
}
}
}
return calendar;
}
private static void printCalendar(String[][] calendar) {
String[] weekdays = {"日", "一", "二", "三", "四", "五", "六"};
System.out.println("日\t一\t二\t三\t四\t五\t六");
for (String[] row : calendar) {
for (String day : row) {
System.out.print(day + "\t");
}
System.out.println();
}
}
private static void saveToFile(String[][] calendar, int year, int month) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
String filename = String.format("%d年%d月日历_%s.txt", year, month, formatter.format(LocalDate.now()));
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
String[] weekdays = {"日", "一", "二", "三", "四", "五", "六"};
writer.write("日\t一\t二\t三\t四\t五\t六\n");
for (String[] row : calendar) {
for (String day : row) {
writer.write(day + "\t");
}
writer.write("\n");
}
System.out.println("日历已保存到文件:" + filename);
} catch (IOException e) {
System.err.println("保存日历到文件失败:" + e.getMessage());
}
}
}
```
你可以按照以下步骤运行代码:
1. 在你的电脑上安装Java开发环境,并配置好环境变量。
2. 创建一个名为`CalendarIO.java`的文件,在文件中复制上述代码。
3. 在终端中进入文件所在的目录,并执行以下命令进行编译:
```bash
javac CalendarIO.java
```
4. 执行以下命令运行程序:
```bash
java CalendarIO
```
5. 接着你会看到提示输入年份和月份,输入后按下回车键即可查看该月份的日历,并保存到文件中。
希望这份代码可以帮到你!
阅读全文