请使用JAVA代码进行 IO练习:从键盘上输入任意年份和月份,输出该月份的日历,并输出到文件中。
时间: 2024-03-11 08:50:48 浏览: 66
好的,这是一个比较实用的IO练习,以下是Java代码实现:
```java
import java.io.*;
public class CalendarIO {
public static void main(String[] args) {
// 从键盘上输入年份和月份
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int year = 0, month = 0;
try {
System.out.print("请输入年份:");
year = Integer.parseInt(br.readLine());
System.out.print("请输入月份:");
month = Integer.parseInt(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
// 输出该月份的日历
String[] weekArr = {"日", "一", "二", "三", "四", "五", "六"};
int[][] daysArr = new int[6][7];
int daysInMonth = getDaysInMonth(year, month);
int firstDayOfWeek = getFirstDayOfWeek(year, month);
int row = 0, col = firstDayOfWeek;
for (int i = 1; i <= daysInMonth; i++) {
daysArr[row][col] = i;
col++;
if (col == 7) {
col = 0;
row++;
}
}
StringBuilder sb = new StringBuilder();
sb.append("日\t一\t二\t三\t四\t五\t六\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < 7; j++) {
sb.append(daysArr[i][j]).append("\t");
}
sb.append("\n");
}
// 输出到文件中
try (PrintWriter writer = new PrintWriter(new FileWriter("calendar.txt"))) {
writer.println(year + "年" + month + "月");
writer.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
// 获取指定年月的天数
private static int getDaysInMonth(int year, int month) {
int days = 0;
switch (month) {
case 2:
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
break;
}
return days;
}
// 获取指定年月的第一天是星期几(0代表星期日)
private static int getFirstDayOfWeek(int year, int month) {
int dayOfWeek = 0;
try {
String dateString = year + "-" + month + "-01";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = sdf.parse(dateString);
java.util.Calendar calendar = java.util.Calendar.getInstance();
calendar.setTime(date);
dayOfWeek = calendar.get(java.util.Calendar.DAY_OF_WEEK) - 1;
} catch (Exception e) {
e.printStackTrace();
}
return dayOfWeek;
}
}
```
这里使用了`BufferedReader`、`StringBuilder`、`PrintWriter`和`FileWriter`等类来实现从键盘输入和输出到文件,需要注意的是,在使用这些类时,我们需要在代码块的最后使用`try-with-resources`语句,以确保资源能够被正确释放。另外,为了实现获取指定年月的天数和第一天是星期几的功能,我们还实现了两个辅助方法:`getDaysInMonth`和`getFirstDayOfWeek`。
阅读全文