【发布时间】:2017-10-26 13:27:53
【问题描述】:
我正在做一个小项目,但遇到了麻烦。它与创建类、构造函数等有关。对于类,所有数据字段都必须是私有的。我还必须有两个构造函数,一个是默认的,一个是参数化的。这是课程:
public class PetInfo {
private String petName = "na";
private boolean petType = true;
private String petBreed = "na";
private double petAge = 0;
private double petWeight = 0;
private String ownerName = "na";
public PetInfo(){}
public PetInfo(String name, boolean type, String breed, double age, double weight, String owner){
this.petName = name;
this.petType = type;
this.petBreed = breed;
this.petAge = age;
this.petWeight = weight;
this.ownerName = owner;
}
public String getName (){
return petName;
}
public void setName(String name){
petName = name;
}
public boolean getType(){
return petType;
}
public void setType(boolean type){
petType = type;
}
public String getBreed(){
return petBreed;
}
public void setBreed(String breed){
petBreed = breed;
}
public double getAge(){
return petAge;
}
public void setAge(double age){
petAge = age;
}
public double getWeight(){
return petWeight;
}
public void setWeight(double weight){
petWeight = weight;
}
public String getOwner(){
return ownerName;
}
public void setOwner(String owner){
ownerName = owner;
}
}
这是我的主要功能:
import java.util.Scanner;
public class Pp1_C00019540 {
public static void main(String[] args) {
PetInfo[] info = new PetInfo[5];
collectInfo(info);
}
public static void collectInfo(PetInfo[] info){
Scanner input = new Scanner(System.in);
for(int i = 0; i < info.length;i++){
System.out.print("Enter pet name: ");
}
}
}
所以它会打印“输入宠物名:”,但它不会让我输入名字。我试着做:
info[i] = new PetInfo(input.nextLine());
但它告诉我“构造函数 PetInfo.PetInfo(String, boolean, String, double,double, String) 不适用。实际参数和形式参数的长度不同。”我的课有什么问题我没听懂吗?我测试了它,它似乎工作正常。
而且我不是在寻找一个明确的答案,我很可能会自己弄清楚。我只是不确定发生了什么,尤其是当我向构造函数传递正确的参数时,这似乎会起作用。
【问题讨论】:
-
这很简单。没有
PetInfo构造函数需要单个String参数。 -
“它告诉我“构造函数 PetInfo.PetInfo(String, boolean, String, double,double, String) 不适用” - 正确,因为你只传递给构造函数一个字符串:@987654326 @
-
@shmosel 我没有使用过具有多个参数的构造函数。因此,即使我在参数化构造函数中传递了 String,我仍然必须创建一个特定的 PetInfo 构造函数,它需要一个参数?我假设这对于 boolean 和 double 参数也同样有效?
-
目前还不完全清楚您要做什么。如果要单独分配每个字段,可以使用零参数构造函数,然后调用设置器。或者您可以收集变量中的所有内容并将它们全部传递给多参数构造函数。或者您可以创建其他构造函数。这取决于你。
-
@shmosel 我必须有一个默认构造函数和一个参数化构造函数,并且对 new 的调用必须导致所有类数据成员都被初始化。所以看起来我需要使用多参数构造函数
标签: java arrays constructor user-input