java中IO练习:从键盘上输入任意年份和月份,输出该月份的日历,并输出到文件中。
时间: 2024-03-11 12:50:41 浏览: 62
java代码-使用java从键盘输入月份,输出这个月的天数,比如输入是1,则输出31天的源代码
5星 · 资源好评率100%
好的,这是一个比较复杂的问题,我来分步骤回答。
首先,我们需要从键盘上读取用户输入的年份和月份。可以使用 `Scanner` 类来实现:
```java
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scanner.nextInt();
System.out.println("请输入月份:");
int month = scanner.nextInt();
```
接着,我们需要计算出该月份的日历。我们可以使用 `Calendar` 类来实现:
```java
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1); // 将日历设置为该年该月的第一天
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 获取该月份的最大天数
int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 获取该月份第一天是星期几
// 输出日历
System.out.printf("%d年%d月\n", year, month);
System.out.println("日\t一\t二\t三\t四\t五\t六");
for (int i = 1; i < firstDayOfWeek; i++) {
System.out.print("\t");
}
for (int i = 1; i <= maxDay; i++) {
System.out.print(i + "\t");
if ((firstDayOfWeek + i - 1) % 7 == 0) {
System.out.println();
}
}
```
最后,我们需要将日历输出到文件中。可以使用 `PrintWriter` 类来实现:
```java
PrintWriter writer = new PrintWriter(new FileOutputStream("calendar.txt"));
writer.printf("%d年%d月\n", year, month);
writer.println("日\t一\t二\t三\t四\t五\t六");
for (int i = 1; i < firstDayOfWeek; i++) {
writer.print("\t");
}
for (int i = 1; i <= maxDay; i++) {
writer.print(i + "\t");
if ((firstDayOfWeek + i - 1) % 7 == 0) {
writer.println();
}
}
writer.close();
```
完整代码如下:
```java
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Scanner;
public class CalendarDemo {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scanner.nextInt();
System.out.println("请输入月份:");
int month = scanner.nextInt();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.printf("%d年%d月\n", year, month);
System.out.println("日\t一\t二\t三\t四\t五\t六");
for (int i = 1; i < firstDayOfWeek; i++) {
System.out.print("\t");
}
for (int i = 1; i <= maxDay; i++) {
System.out.print(i + "\t");
if ((firstDayOfWeek + i - 1) % 7 == 0) {
System.out.println();
}
}
PrintWriter writer = new PrintWriter(new FileOutputStream("calendar.txt"));
writer.printf("%d年%d月\n", year, month);
writer.println("日\t一\t二\t三\t四\t五\t六");
for (int i = 1; i < firstDayOfWeek; i++) {
writer.print("\t");
}
for (int i = 1; i <= maxDay; i++) {
writer.print(i + "\t");
if ((firstDayOfWeek + i - 1) % 7 == 0) {
writer.println();
}
}
writer.close();
}
}
```
希望能够帮到你!
阅读全文