【发布时间】:2011-03-30 14:19:57
【问题描述】:
我正在尝试从 .txt 文件中读取双精度并将它们全部放入一个列表中。
这是我目前的代码 ->
(我有一种方法可以请求文件并获取数据流,还有一种方法可以将双精度数据放入列表中。)
public InputFile () throws MyException {
fileIn = null;
dataIn = null;
do {
filename = JOptionPane.showInputDialog("What is the file called? ");
try {
fileIn = new FileInputStream((filename + ".txt"));
dataIn = new DataInputStream(fileIn);
return;
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "There is no "+filename + ".txt");
}
}
while ( Question.answerIsYesTo("Do you want to retype the file name") );
throw new MyException("No input file was chosen");
}
这部分工作正常。
public ProcessMain() {
boolean EOF = false;
List <Double> allNumbers = new ArrayList <Double> () ;
try {
InputFile inputFile = new InputFile();
while(EOF == false) {
try {
allNumbers.add(inputFile.dataIn.readDouble());
}
catch(EOFException e){ EOF = true; }
}
// List manipulation here. I have no problems with this part.
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(allNumbers);
我得到以下信息 -
java.lang.IndexOutOfBoundsException:索引:0,大小:0
有什么想法吗?
【问题讨论】:
-
InputFile2是什么?你的意思是InputFile inputFile2 = new InputFile()?哪一行代码抛出异常? -
是的,我把 2 放错了。
-
哪一行抛出异常?
-
您不应该使用
new Double()构造函数。您可以将double直接传递给allNumbers.add(),它将autoboxed 传递给Double。如果您想明确地将double装箱,请使用Double#valueOf()而不是new Double()- 在这种情况下您不需要自己解析字符串,因为Double#valueOf()可以接受一个字符串。 -
好的,所以我不再遇到异常,但唯一的输出是'[]'。谢谢。
标签: java list double text-files