我觉得至少打印出每个子类的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());
}
}
}
答案 0 :(得分:0)
此代码中的问题是字符串比较。请使用unit.equalsIgnoreCase(“Inch”)代替unit.equals(“Inch”)等。更正代码:
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.equalsIgnoreCase("Meter")) {
length = new Meter(value);
lo.add(length);
} else if (unit.equalsIgnoreCase("Foot")) {
length = new Foot(value);
lo.add(length);
} else if (unit.equalsIgnoreCase("Inch")) {
length = new Inch(value);
lo.add(length);
} else if (unit.equalsIgnoreCase("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());
}
}
}
答案 1 :(得分:0)
单位字符串比较中的代码存在两个问题。
其他答案提到,在代码中你正在使用“英寸”,而在文件中你正在使用“英寸”。可以使用equalsIgnoreCase()
即使您更改了1,您仍将面临阅读不完整文件的问题。原因是在文件中,您将遇到单数和复数单位名称。它可以通过像if (unit.equalsIgnoreCase("foot") || unit.equalsIgnoreCase("feet"))