【发布时间】:2014-10-24 12:24:08
【问题描述】:
我是初学者,我有一个 txt 文件,用户将导入到 java 中,我将读取 txt 文件 line be line 然后在每一行设置变量 base 并将它们添加到当前记录中
public void importTXT() {
JFileChooser fc = new JFileChooser();
fc.setAcceptAllFileFilterUsed(false);
fc.setMultiSelectionEnabled(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"TEXT FILES", "txt", "text");
fc.setFileFilter(filter);
int returnVal = fc.showOpenDialog(CollectionFrame.this);
String[] numstrs = null;
if (returnVal == JFileChooser.APPROVE_OPTION) {
File importedFile = fc.getSelectedFile();
try {
Scanner sc = new Scanner(importedFile);
while (sc.hasNextLine()) {
numstrs = sc.nextLine().split("\\s+"); // split by white
// space
}
} catch (IOException e) {
}
// add new collection
Collection newCollection = new Collection(numstrs[0]);
allRecord.addCollection(newCollection);
// add art consignment information
String consignmentName = numstrs[3];
String description = numstrs[4];
我在倒数第二行收到了ArrayIndexOutOfBoundsException
String consignmentName = numstrs[3];
文本文件的内容是这样的:
Richman’s Estate Collection
5
ART
Water Lilies
A superb piece in great condition
谁能告诉我怎么了?
【问题讨论】:
-
表示数组 numstrs 的元素少于 4 个。尝试使用 numstrs.length
-
Collection newCollection = new Collection(numstrs[0]);应该做什么?你有自己的类型叫Collection吗?因为java.util中的Collection是一个接口 -
先检查
numstrs.length>4 -
你应该使用调试器
-
你知道把它放在循环之外你只使用最后一行并尝试使用它。当你用空格分割时检查最后一行不会有4个元素。