首页 > 解决方案 > 构造函数未被识别

问题描述

当我运行程序时,我得到:构造函数 Package() 未定义,构造函数 InsuredPackage() 未定义 Package 和 InsuredPackage 类工作正常,没有问题,主要是给我带来麻烦。包 a = new Package(); 和 InsuredPackage b = new InsuredPackage(); 有下划线。

import java.io.*;
import java.util.*;

public class homework06
{
    public static void main(String[] args)
    {
        ArrayList<String> simple = new ArrayList<String>();
        ArrayList<String> insured = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        boolean bool = true;
        while(bool == true)
        {
            System.out.println("Choose Option:");
            System.out.printf("1. Simple Package\n2. Insured Package\n3. Exit\n");
            int x = sc.nextInt();
            if(x == 1)
            {
                Package a = new Package();
                a.id = sc.next();
                a.weight = sc.nextDouble();
            }
            else if(x == 2)
            {
                InsuredPackage b = new InsuredPackage();
                b.id = sc.next();
                b.weight = sc.nextDouble();
            }
            else if(x == 3)
            {
                bool = false;
            }
        }
        sc.close();
    }    
}

public class Package
{
    String id;
    double weight;

    public Package(String id,double weight)
    {
        this.id = id;
        this.weight = weight;
    }

    public String getID()
    {  
        return id;

    }

    public double getW()
    {
        return weight;
    }

    public double computeCost()
    {
        double charge=0;
        if(weight>0 && weight<=3)
        {
            charge = 3;
        }
        else if(weight>3)
        {
            charge = 3 + (0.7*(weight-3));
        }
        return charge;
    }

    public String toString()
    {
        return id + "," + weight + "," + computeCost();
    }

}

public class InsuredPackage extends Package
{    
    public InsuredPackage(String id,double weight)
    {
        super(id,weight);
    }

    public double computeCostExtra()
    {
        double extra=0;
        double charge = computeCost();
        if(charge>0 && charge<=5)
        {
            extra = 2;
        }
        else if(charge>5 && charge<=10)
        {
            extra = 3;
        }
        else if(charge>10)
        {
            extra = 5;
        }
        return charge + extra;
    }
    
    public String toString()
    {
        return id + "," + weight + "," + computeCostExtra();
    }
}



标签: java

解决方案


如果您尚未在类中声明任何构造函数,Java 将创建默认构造函数。默认构造函数是无参数构造函数。

InsuredPackagePackage类中,您都创建了带有参数的构造函数。因此 java 不会创建默认构造函数,但您在代码中调用了无参数构造函数。

InsuredPackage b = new InsuredPackage();

Package a = new Package();

您需要在 classes 中创建无参数构造函数


推荐阅读