import java.util.*; public class Date { private int year; private int month; private int day; public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public int getDayOfYear() { int[] daysOfMonth = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; int dayOfYear = daysOfMonth[month - 1] + day; if (isLeapYear() && month > 2) { dayOfYear++; } return dayOfYear; } public boolean isLeapYear() { if (year % 4 == 0) { if (year % 100 == 0) { return year % 400 == 0; } else { return true; } } else { return false; } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int year = scan.nextInt(); int month = scan.nextInt(); int day = scan.nextInt(); Date date = new Date(year, month, day); System.out.println(date.getDayOfYear()); } }报错:Main.java:3: error: class Date is public, should be declared in a file named Date.java public class Date { ^ 1 error,修改代码
时间: 2024-02-14 15:19:35 浏览: 174
你需要将 `Date` 类保存到一个名为 `Date.java` 的文件中,并在 `Main.java` 中使用它。在 `Main.java` 文件中,你可以使用 `import` 语句来导入 `Date` 类。
下面是修改后的代码:
Date.java 文件:
```java
public class Date {
private int year;
private int month;
private int day;
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getDayOfYear() {
int[] daysOfMonth = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
int dayOfYear = daysOfMonth[month - 1] + day;
if (isLeapYear() && month > 2) {
dayOfYear++;
}
return dayOfYear;
}
public boolean isLeapYear() {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
} else {
return true;
}
} else {
return false;
}
}
}
```
Main.java 文件:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int year = scan.nextInt();
int month = scan.nextInt();
int day = scan.nextInt();
Date date = new Date(year, month, day);
System.out.println(date.getDayOfYear());
}
}
```
阅读全文