【发布时间】:2014-02-18 04:41:37
【问题描述】:
我觉得至少打印出每个子类的 toString 方法是正确的,但由于某种原因,它导致什么都没有打印出来。任何帮助将不胜感激。
数据.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码
-
请勿在此处发布。编辑您的问题并将其添加到那里,格式化。
-
您的
toString()方法在Length类中是什么样的? -
myLengths = lo.toArray()无需 for 循环来创建数组
标签: java arrays object arraylist