微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

运行程序时找不到主类

如何解决运行程序时找不到主类

我无法运行这个程序:

练习 7.13 JHTP(日期类):创建一个名为 Date 的类 包括 3 个实例变量——一个月(int 类型)、一天(int 类型)、 和一年(int 型)。提供一个构造函数来初始化 3 实例变量并假定提供的值是正确的。 为每个实例变量提供一个 set 和一个 get 方法。提供一个 方法 displayDate 显示月、日和年,由 正斜杠(/)。

我的代码

public class Date {

    private int month;
    private int day;
    private int year;
    
    public Date(int month,int day,int year){//constructor
        this.month = month;//initilize 
        this.day = day;
        this.year = year;
    }
    
    public void setMonth(int month){
        this.month = month;//stores the names
    }
    public void setDay(int day){
        this.day = day;
    }
    public void setYear(int year){
        this.year = year;
    }
    public int getMonth(){
        return month;//return value

    }
    public int getDay(){
      return day;
    }
    public int getYear(){
        return year;
    }
    public String displayDate(){

        return month + "/" + day + "/" + "/" + year;
   

    }
}

我尝试添加 public static void main(String[] args),但是出现了一堆错误

解决方法

只需在类中添加一个 main 方法即可。

public class Date {

    private int month;
    private int day;
    private int year;

    public Date(int month,int day,int year){//constructor
        this.month = month;//initilize
        this.day = day;
        this.year = year;
    }

    public void setMonth(int month){
        this.month = month;//stores the names
    }
    public void setDay(int day){
        this.day = day;
    }
    public void setYear(int year){
        this.year = year;
    }
    public int getMonth(){
        return month;//return value

    }
    public int getDay(){
        return day;
    }
    public int getYear(){
        return year;
    }
    public String displayDate(){

        return month + "/" + day + "/" + "/" + year;


    }

    public static void main(String[] args) {
        Date date = new Date(11,11,1991);
        System.out.println(date.displayDate());
    }
}

如果您使用的是 InteliJ,要运行代码,请在 main 方法内部右键单击并“运行 Date.main()”

这有利于测试目的,但在实际程序中,您将在包中的其他类中调用 Date 类。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。