Java 为什么';我的新对象不能在我的主方法中工作吗?
•将代码添加到main,以创建名为birthday的新日期对象。新对象 应该包含你的生日。您可以使用任一构造函数。添加代码以打印测试日期 •向main添加代码,以创建名为today的新日期对象。新对象应包含您的今天日期。您应该使用另一个构造函数。添加代码以打印测试日期 我已经做了所有这些,我不知道为什么,但我的主要方法不起作用?如何在main中格式化代码以创建新对象Java 为什么';我的新对象不能在我的主方法中工作吗?,java,Java,•将代码添加到main,以创建名为birthday的新日期对象。新对象 应该包含你的生日。您可以使用任一构造函数。添加代码以打印测试日期 •向main添加代码,以创建名为today的新日期对象。新对象应包含您的今天日期。您应该使用另一个构造函数。添加代码以打印测试日期 我已经做了所有这些,我不知道为什么,但我的主要方法不起作用?如何在main中格式化代码以创建新对象 class Date { int year;//the next three lines are for the secon
class Date {
int year;//the next three lines are for the second bullet point
int month;
int day;
int birthday;
int today;
public Date() {//this is the constructor that takes no parameters
this.year = 0;
this.month = 0;
this.day = 0;
}
public Date(int year, int month, int day, int birthday, int today) { //this is for the thirs bullet point on assignment
this.year = year;
this.month = month;
this.day = day;
this.birthday = birthday;
this.today = today;
}
public class MoreDates {
public void printDate(Date date) {//this is for the fourth bullet point.
System.out.println(date.year);
System.out.println(date.month);
System.out.println(date.day);
System.out.println(date.birthday);
System.out.println(date.today);
}
public void main(String[] args) {
this.birthday = 17;
this.today = 29;
}
}
}
您的主要方法不是静态的。因此,当您尝试执行程序时,JVM不会运行它。在Java中,您使用关键字“new”创建一个新对象,您的it应该如下所示
Date birthday=new Date();
代码中的关键错误:
您将main方法作为嵌套类的一部分。在Java中,文件名应该与具有main方法的类名匹配。示例:如果主方法存在于名为moreDates的类中,则文件名应为moreDates.java
JVM通过其语法识别主方法,预期语法为
public static void main(String[] args) {
}
解决了我的问题:
class Date {
int year;//the next three lines are for the second bullet point
int month;
int day;
int birthday;
int today;
public Date() {//this is the constructor that takes no parameters
this.year = 0;
this.month = 0;
this.day = 0;
}
public Date(int year, int month, int day) { //this is for the thirs bullet point on assignment
this.year = year;
this.month = month;
this.day = day;
}
}
public class MoreDates {
public static void printDate(Date date) {//this is for the fourth bullet point.
System.out.println(date.year);
System.out.println(date.month);
System.out.println(date.day);
System.out.println(date.birthday);
System.out.println(date.today);
}
public static void main(String[] args) {
Date birthday = new Date(1998,11,17);
Date today = new Date(2016,11,29);
printDate(birthday);
printDate(today);
}
}
您的
main
方法除了指定生日
和今天
之外什么都不做。此外,main必须是公共静态void
-您的不是。欢迎使用堆栈溢出。请把这个问题简化为一个问题——目前,你已经包含了大量代码和与你的作业无关的细节,但真正重要的一点是,你所说的错误只是“我的主要方法不起作用”。请仔细阅读,并记住堆栈溢出的目的是创建一个高质量问题和答案的存储库。你说你“已经完成了所有这些”,但你没有在main方法中创建日期对象。当我添加static时,它会说who方法不正确?@Lexi yes,因为静态方法不能引用非静态内容。除了使方法静态之外,还需要进行更多的重构,但是非静态的main
方法是它无法运行的原因。