以下是我用来从文件读取并将代码的详细信息保存在两个类ArrayList
和Iphone
的{{1}}中的代码,但是显然这有问题。
此代码的输出为:
Ipad
的Iphone @ 28d93b30和IndexOutOfBoundException
ipads.get(0)
文件如下:
try {
fScanner = new Scanner(new File("apple.txt"));
}
catch (FileNotFoundException e) {
System.out.println(e.toString());
}
ArrayList<Iphone> iphones = new ArrayList<>();
ArrayList<Ipad> ipads = new ArrayList<>();
while(fScanner.hasNextLine()) {
String line = fScanner.nextLine();
Scanner lineScanner = new Scanner(line);
if(lineScanner.next().equals("IPHONE")) {
String model = "IPHONE"+lineScanner.useDelimiter(",").next();
String scrSze = lineScanner.useDelimiter(",").next();
String proc = lineScanner.useDelimiter(",").next();
String simT = lineScanner.useDelimiter(",").next();
String clr = lineScanner.useDelimiter(",").next();
String rom = lineScanner.useDelimiter(",").next();
String is3dtouch = lineScanner.useDelimiter(",").next();
String pric = lineScanner.useDelimiter(",").next();
iphones.add(new Iphone(model,scrSze,proc,simT,clr,rom,is3dtouch,pric));
}
else if(lineScanner.next().equals("IPAD")) {
String model = "IPAD"+lineScanner.useDelimiter(",").next();
String scrSze = lineScanner.useDelimiter(",").next();
String proc = lineScanner.useDelimiter(",").next();
String iswifi = lineScanner.useDelimiter(",").next();
String clr = lineScanner.useDelimiter(",").next();
String memo = lineScanner.useDelimiter(",").next();
String pric = lineScanner.useDelimiter(",").next();
ipads.add(new Ipad(model,scrSze,proc,iswifi,clr,memo,pric));
}
}
System.out.println(iphones.get(2)+"\n");
System.out.println(ipads.get(0)+"\n");
我希望能很好地解释上述问题。
答案 0 :(得分:2)
您得到Iphone@28d93b30
是因为您正在打印Iphone,并且没有覆盖Iphone类中的toString()
方法,这意味着默认的Object.toString()
方法正在执行
出现异常是因为您试图获取列表中的第一个Ipad,但列表中没有任何Ipad。完全没有,因为您要两次调用next()
(一次在第一个if
条件下调用一次,然后在第二个else if
条件下调用一次,因此要与“ IPAD”进行比较的令牌“是该行的第二个,而不是第一行。