请使用JAVA代码处理IO练习:从键盘上输入任意年份和月份,输出该月份的日历,并输出到文件中。
时间: 2024-03-11 07:51:11 浏览: 68
好的,以下是处理IO的JAVA代码:
```java
import java.util.Scanner;
import java.io.*;
public class Calendar {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入年份:");
int year = input.nextInt();
System.out.print("请输入月份:");
int month = input.nextInt();
// 计算该月份的天数
int days = getDaysOfMonth(year, month);
// 输出该月份的日历
printCalendar(year, month, days);
// 输出到文件中
try {
FileWriter writer = new FileWriter("calendar.txt");
writer.write("年份:" + year + " 月份:" + month + "\n");
writer.write("日 一 二 三 四 五 六\n");
int dayOfWeek = getDayOfWeek(year, month, 1);
for (int i = 1; i <= days; i++) {
if (i == 1) {
for (int j = 1; j <= dayOfWeek; j++) {
writer.write(" ");
}
}
writer.write(String.format("%2d ", i));
if ((dayOfWeek + i) % 7 == 0) {
writer.write("\n");
}
}
writer.close();
System.out.println("日历已输出到文件calendar.txt中。");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取指定年份月份的天数
*/
public static int getDaysOfMonth(int year, int month) {
int days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
}
return days;
}
/**
* 获取指定日期是星期几
*/
public static int getDayOfWeek(int year, int month, int day) {
if (month == 1 || month == 2) {
month += 12;
year--;
}
int c = year / 100;
int y = year % 100;
int m = month;
int d = day;
int w = (y + y / 4 + c / 4 - 2 * c + 26 * (m + 1) / 10 + d - 1) % 7;
return (w + 7) % 7;
}
/**
* 输出指定年份月份的日历
*/
public static void printCalendar(int year, int month, int days) {
System.out.printf("%d年%d月\n", year, month);
System.out.println("日 一 二 三 四 五 六");
int dayOfWeek = getDayOfWeek(year, month, 1);
for (int i = 1; i <= days; i++) {
if (i == 1) {
for (int j = 1; j <= dayOfWeek; j++) {
System.out.print(" ");
}
}
System.out.printf("%2d ", i);
if ((dayOfWeek + i) % 7 == 0) {
System.out.println();
}
}
System.out.println();
}
}
```
使用以上代码,会将日历输出到控制台,并且将日历输出到文件calendar.txt中。
阅读全文