我覺得這樣做至少可以打印出每個子類的toString方法,但由於某些原因,它不會打印任何內容。任何幫助將不勝感激。爲什麼我不打印對象的循環?
data.txt中:
1 meter
1 inch
1 foot
1 yard
401.336 meters
15839 inches
1319 feet
439 yards
代碼
public abstract class Length implements Comparable<Length> {
public String toString() {
return this.getClass() + ": " + getLength() + " " + getUnit();
}
public static void main(String[] args){
ArrayList<Length> lo = new ArrayList <Length>();
Scanner in = null;
try {
in = new Scanner(new File("src/length/data.txt"));
} catch (FileNotFoundException exception) {
throw new RuntimeException("failed to open data.txt");
}
// need more code for other parts of this assignment
while (in.hasNextDouble()) {
double value = in.nextDouble();
String unit = in.next();
Length length = null;
if(unit.equals("Meter")){
length = new Meter(value);
lo.add(length);
}
else if(unit.equals("Foot")){
length = new Foot(value);
lo.add(length);
}
else if(unit.equals("Inch")){
length= new Inch(value);
lo.add(length);
}
else if(unit.equals("Yard")){
length = new Yard(value);
lo.add(length);
}
}
Length[] myLengths = new Length[lo.size()]; //declares myLengths integer array
for(int i=0; i < lo.size(); i++){
myLengths[i]=lo.get(i); //copies arrayList to lo to Length array myLengths
}
for(int i = 0; i < myLengths.length; i++) {
System.out.println(myLengths[i].toString());
}
}
}
你的文件包含什麼?好像'myLengths.length'爲0 –
這是data.txt中1米 1英寸 1英尺 1碼 401.336米 15839英寸 1319英尺 439碼 –
不要在這裏發佈的內容。編輯你的問題,並將其添加,格式化。 –