java - 构造函数未被识别
问题描述
当我运行程序时,我得到:构造函数 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 将创建默认构造函数。默认构造函数是无参数构造函数。
在InsuredPackage
和Package
类中,您都创建了带有参数的构造函数。因此 java 不会创建默认构造函数,但您在代码中调用了无参数构造函数。
InsuredPackage b = new InsuredPackage();
和
Package a = new Package();
您需要在 classes 中创建无参数构造函数。
推荐阅读
- excel - 工作簿表复制到多个工作簿并重命名
- netsuite - NetSuite:从 Suitecommerce 站点获取信息到用户事件脚本
- ios - 在另一个 View Xcode 中显示 ViewController
- c# - PDFClown 无法编辑创建的 PDF
- scala - 具有树结构的 Akka 流
- javascript - 无法在 XmlHttpRequest 中分配“Access-Control-Allow-Origin”
- dart - 有什么方法可以在颤振中创建 3D 图表
- ios - 在 ARKit 中何时使用 worldTransform() 以及何时使用 transform()
- javascript - 值未更新
- python - 多个异步循环