![](/img/trans.png)
[英]My array index is out of bounds when populating a 2d array using a csv file
[英]Array Index out of bounds when reading from CSV file
我正在尝试使用BufferedReader
读取CSV文件,但是由于某些原因,我在7行之后出现了超出范围的异常。 我在另一个CSV文件(30行)上尝试了这种精确算法,并且工作正常。 这是有问题的CSV文件。
String spellPath = "file path is here";
FileReader y = new FileReader(spellPath);
BufferedReader x = new BufferedReader(y);
ArrayList<Card> ArrayList = new ArrayList<Card>( ); //dynamic data type
for( String p = x.readLine(); p != null ; p = x.readLine()){
String [] stArray = p.split(",");
ArrayList.add(new Card( stArray[1], stArray[2])); //new card with name and desc only
}
System.out.println(ArrayList.toString());
文件有问题还是算法有问题?
您的问题是连续两次调用p = x.readLine()
for( String p = x.readLine(); p != null ; p = x.readLine()){
...
}
因此,将读取2行,并且仅检查1行是否为空
您需要将循环更改为
while (true) {
String p= x.readLine();
if (p == null) break;
...
}
一行“您在场上的每张法术卡都能获得500 ATK和DEF”。 不包含任何,
。 因此stArray[]
的长度为1。
另一件事:Java数组为零基。
并且for( String p = x.readLine(); p != null ; p = x.readLine()){
应该是while ((String p = x.readLine())!= null ){
尝试这个。
while(x.readLine() != null){
---`enter code here`
}
您在循环中两次调用x.readLine()
。 因此,您在阅读时跳过了几行。
更好的方法是使用CSVReader而不是缓冲的阅读器。
CSVReader reader = new CSVReader(new FileReader(fName), ',','"','|');
List content = reader.readAll();//do not use this if CSV file is large
String[] row = null;
for (Object object : content) {
row = (String[]) object;
row = Arrays.toString(row).split(",");
//now you have a row array with length equal to number of columns
}
这是获取CSVReader的链接-CSVReader下载
while((String p = x.readLine()) != null){
String [] stArray = p.split(",");
ArrayList.add(new Card( stArray[0], stArray[1])); //new card with name and desc only
}
System.out.println(ArrayList.toString());
这应该工作
错误在这里抛出
String [] stArray = p.split(",");
ArrayList.add(new Card( stArray[1], stArray[2]));
添加此条件并检查
String [] stArray = p.split(",");
ArrayList.add(new Card( stArray[0], stArray[1]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.