You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java报错The constructor is undefined 重载构造器未定义问题求助

错误原因

  • 字符类型传参错误:Java中char类型的字面量必须用单引号包裹,你在实例化对象时,给char类型的author、section2参数传入了双引号包裹的"C"、"P"、"E",这些实际是String类型,和你定义的构造方法参数列表不匹配,因此编译器找不到对应构造方法,触发The constructor is undefined报错。
  • 浮点类型不匹配:Java中浮点数字面量默认是double类型,你实例化book2时传入的185.86是double类型,和第二个构造方法要求的float类型不匹配,也会导致参数匹配失败。
  • 冗余错误:代码中调用了s.close(),但你从未定义过名为s的变量,运行时也会抛出异常。

解决方法

  1. 把所有传入char参数的双引号改为单引号:将"C"改为'C'、"P"改为'P'、"E"改为'E',匹配构造方法的参数类型。
  2. 给浮点参数185.86添加后缀f,转为float类型,匹配第二个构造方法的参数要求。
  3. 删除无意义的s.close()语句,你当前代码没有用到IO相关逻辑,无需该操作。

修正后可运行代码

class Book { 
    String section;
    float subject2;
    char section2, author;
    int subject, author2, year;

    Book(String section, int subject, char author, int author2, int year) { 
        this.section = section;
        this.subject = subject;
        this.author = author;
        this.author2 = author2;
        this.year = year;
    }
    Book(char section2, float subject2, char author, int author2, int year) {
        this.section2 = section2;
        this.subject2 = subject2;
        this.author = author;
        this.author2 = author2;
        this.year = year;
    }
    void displayData() {
        System.out.println(section + subject + " ." + author + author2 + " " + year);
    }
    void displayData2() {
        System.out.println(section2 + subject2 + " ." + author + author2 + " " + year);
    }
}
public class TestBook {
    public static void main(String[] args) {
        Book book1 = new Book("LB", 2395, 'C', 65, 1991);
        Book book2 = new Book('E', 185.86f, 'P', 277, 2010);
        book1.displayData();
        book2.displayData2();
    }
}

内容的提问来源于stack exchange,提问作者PJ Villaflor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:45:01