我的老师让我填补了一些代码的麻烦。
我有类Car,然后是另外2个子类,LightCar和heavyCar将扩展Car类。 基本上我得到了这样的东西:
public abstract class Car{
public static Car newCar(File file) throws FileNotFoundException {
carType = null;
Scanner in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
String tokens[] = line.split(";");
if (line.contains("Light Weight")) {
LightCar lightC = new LightCar(Long
.valueOf(tokens[1]).longValue(), tokens[3]);
in.close();
carType = lightC;
}
if (line.contains("Heavy Weight")) {
HeavyCar heavyC = new HeavyCar(Long.valueOf(
tokens[1]).longValue(), tokens[3]);
in.close();
carType = heavyC;
}
}
in.close();
return carType;
}
public getLicense(){
return.. // PROBLEM HERE
}
}
public getCarColor(){
return.. PROBLEM HERE
}
}
我应该读取包含所有这些信息的文件。
我的一个大问题是,如果我有这样的静态工厂方法,我该如何使用这些get函数? 我在尝试获取这些信息时遇到了麻烦,我会喜欢这方面的一些提示。
我也获得了一些JTestUnits,例如:
Car c = new LightCar(3, "Volvo");
assertEquals(c.getColor(), "Red");
答案 0 :(得分:0)
您必须向抽象类添加两个属性(许可证和颜色)。 您的子类现在有两个新属性以及getter和相关的setter。
public abstract class Car{
private String licence;
private String color;
public static Car newCar(File file) throws FileNotFoundException {
carType = null;
Scanner in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
String tokens[] = line.split(";");
if (line.contains("Light Weight")) {
LightCar lightC = new LightCar(Long
.valueOf(tokens[1]).longValue(), tokens[3]);
//Read here the color and the licence
lightC.setColor(...);
lightC.setLicence(...);
//replace "..." by your value
in.close();
carType = lightC;
}
if (line.contains("Heavy Weight")) {
HeavyCar heavyC = new HeavyCar(Long.valueOf(
tokens[1]).longValue(), tokens[3]);
//same as above
in.close();
carType = heavyC;
}
}
in.close();
return carType;
}
public String getLicense(){
return licence;
}
public void setLicence(String licence){
this.licence=licence;
}
public String getCarColor(){
return color;
}
public void setColor(String color){
this.color=color;
}
}