first_day local variable assignment is controlled by if and for. if if for is entered, first_day is unassigned. The default value is 0
import java.util.Scanner;
public class MyCalendar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("如果您想查看某年的日历,请输入1");
System.out.println("如果您想查看某天的星期,请输入2");
int user_input = scanner.nextInt();
if (user_input == 1) {
int year = scanner.nextInt();
//已知2023年一月一日是星期日
int temp;
int first_day;
if (year < 2023) {
for (int i = year; i < 2023; i++) {
int days = 0;
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
days += 366;
} else {
days += 365;
}
temp = days % 7;
first_day = 7 - temp; //每年的1月1日是星期几
if (temp == 0) {
first_day = 0; //将星期日记作0
}
}
} else if (year == 2023) {
first_day = 0; //2023一月一日是星期日
} else {
int days = 0;
for (int i = 2023; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
days += 366;
} else {
days += 365;
}
temp = days % 7;
first_day = temp;
}
}
int day = 1;
int[] a;
if (year % 4 == 0 && year % 100 != 0 || year % 400 ==0) {
a = new int[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
} else {
a = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
}
int m;
for (m = 1; m <= 12; m++) {
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
for (int i = 0; day < a[m]; day++) {
for (int j = 0; j < first_day; j++) {
}
}
}
} else if (user_input == 2) {
} else {
System.out.println("请输入有效的数字!");
}
}
}
Write an interactive system, users enter the year to see the calendar, enter the date to see the week.
The program is not finished yet, and I'm writing the first part. I defined a first_day to indicate the day of January 1st of the input year. first_day is a local variable, but I assigned it to all if else, but I reported an error in the later loop: first_day might not be initialized yet. What's going on? How do I fix it? Comment if < br / >
< div class = "aw - list - img >
I began to learn Java in the second semester of my freshman year, and I learned C in the last semester. Some people say that my code style is a little messy and I have obvious habits of C programming. May I ask how do you plan/design your own code?
0 Answer
first_day local variable assignment is controlled by if and for. if if for is entered, first_day is unassigned. The default value is 0
You can initialize a default value of 0 when you define firstDay. Your code will only assign a value to firstDay if certain conditions are met, so you may not initialize it at all.
hope to adopt
Local variables in java need to be initialized. Remember that first_day is a local variable, so you can give it a default value of 0 or something when you declare it.
As for the code style, it is recommended to look at the Alibaba java development specification, you this variable naming convention is indeed c, java is generally a hump
这家伙很懒,什么都没留下...