•向main添加代码,创建名为birthday的新Date对象。新对象 应该包含你的生日。您可以使用任一构造函数。添加代码以打印日期以进行测试。
•向main添加代码,以创建名为today的新Date对象。新对象应包含您今天的日期。您应该使用其他构造函数。添加代码以打印日期以进行测试。
我已经完成了所有这些并且我不确定为什么但是我的主要方法不起作用?如何在main中格式化我的代码以创建新对象?
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;
}
}
}
答案 0 :(得分:1)
在Java中,您使用关键字“new”创建一个新对象,它应该看起来像这样
Date birthday=new Date();
代码中的关键错误: 您将main方法作为嵌套类的一部分。在Java中,文件名应与具有main方法的类名匹配。示例:如果您的main方法存在于名为moreDates的类中,则文件名应为moreDates.java。
JVM通过它的语法识别主方法,期望的语法是
public static void main(String[] args) {
}
答案 1 :(得分:1)
解决了我的问题:
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);
}
}
答案 2 :(得分:0)
您的主要方法不是static
。因此,当您尝试执行程序时,JVM不会运行它。