gpt4 book ai didi

java - 为什么ArrayList返回错误: ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-11-29 03:03:08 25 4
gpt4 key购买 nike

不知道为什么。我逐行读取我的文本文件,通过拆分剪切行并将它们保存到 ArrayList。但是如果文件超过 100 行,我的程序就无法运行,所以它在 split 命令时返回错误。我想知道我的电脑是否内存不足?

各位,谁能说得清楚呢?提前谢谢你。这是我的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
class Vocab implements Comparable<Vocab>{
private String vocab;
private String explanation;
public Vocab(String vocab, String explanation) {
this.vocab = vocab;
this.explanation = explanation;
}
public int compareTo(Vocab that){
return this.vocab.compareTo(that.vocab);
}
public String getVocab() {
return vocab;
}
public void setVocab(String vocab) {
this.vocab = vocab;
}
public String getExplanation() {
return explanation;
}
public void setExplanation(String explanation) {
this.explanation = explanation;
}
}
public class Test {
public static void readFile(String fileName, ArrayList<String> a) throws FileNotFoundException {
try {
File fileDir = new File(fileName);
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
String str;
while((str= in.readLine())!= null){
a.add(str);
}
in.close();
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null,"Something in database went wrong");
}
}
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
ArrayList<Vocab> a= new ArrayList<Vocab>();
ArrayList<String> b= new ArrayList<String>();
readFile("DictVE.dic",b);
for (String t: b){
String[] temp= t.split(":");
a.add(new Vocab(temp[0].trim(), temp[1].trim()));// error in here
}
}
}

这是我的文件:DictEV.dic

最佳答案

String.split(String) method 中有一个微妙的问题, 即从字符串末尾丢弃空标记:

Trailing empty strings are therefore not included in the resulting array.

所以:

System.out.println("Hello:".split(":").length); // Prints 1.

您可以通过将负整数作为第二个参数传递来保留空字符串:

System.out.println("Hello:".split(":", -1).length); // Prints 2.

关于java - 为什么ArrayList返回错误: ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33633000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com