Java:处理文件时ArrayList越界

huangapple go评论79阅读模式
英文:

Java: Arraylist out of bounds when processing file

问题

import java.io.*;
import java.util.*;

public class BankRecords {
    // ... (remaining code)

    public static void main(String args[]) {
        readData();
    }
}

abstract class Client {
    static ArrayList<List<String>> BankArray = new ArrayList<>(25);
    static BankRecords[] robjs = new BankRecords[600];

    public static void readData() {
        try {
            BufferedReader br;
            String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
            br = new BufferedReader(new FileReader(new File(filepath)));
            String line;
            while ((line = br.readLine()) != null) {
                BankArray.add(Arrays.asList(line.split(",")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        processData();
    }

    public static void processData() {
        int idx = 0;
        for (List<String> rowData : BankArray) {
            robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
            robjs[idx].setId(rowData.get(0));
            robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
            idx++;
        }
        printData();
    }

    public static void printData() {
        System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
        int final_record = 24;
        for (int i = 0; i < final_record; i++) {
            System.out.println(BankArray.get(i) + "\t ");
        }
    }
}

Please note that the provided code is a direct translation of your original code into Chinese. If you have any specific issues or questions about the code, feel free to ask.

英文:

I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.

My code so far.

The BankRecords class

import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId() 
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried() 
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.save_act = save_act;
}
public String getCurrent_act() 
{
return current_act;
}
public void setCurrent_act(String current_act)
{
this.current_act = current_act;
}
public String getMortgage() 
{
return mortgage;
}
public void setMortgage(String mortgage) 
{
this.mortgage = mortgage;
}
public String getPep()
{
return pep;
}
public void setPep(String pep)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age) 
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome() 
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}

The Client abstract class

 import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList&lt;List&lt;String&gt;&gt; BankArray = new ArrayList&lt;&gt;(25); 
static BankRecords robjs[] = new BankRecords[600]; 
public static void readData()
{
try
{
BufferedReader br;
String filepath = &quot;C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv&quot;;
br = new BufferedReader(new FileReader  (new File(filepath)));
String line;   
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(&quot;,&quot;)));
}	
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List&lt;String&gt; rowData: BankArray) 
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1))); 
idx++;
}
printData(); 
}
public static void printData() 
{
System.out.println(&quot;ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE&quot;);
int final_record = 24;
for (int i = 0; i &lt; final_record; i++)
{
System.out.println(BankArray.get(i) + &quot;\t &quot;);
}
}
}

The BankRecordsTest class (extends Client)

  import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}

The error

And here is the error.

Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)

I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.

答案1

得分: 0

我认为你的数据可能不干净,而且你对数组的长度做出了假设。你得到的错误源自于这一行代码:

        robjs[idx].setAge(Integer.parseInt(rowData.get(1))); 

很明显,rowData没有2个或更多的项目。这就是为什么你会得到ArrayIndexOutOfBoundsException。所以你需要检查一下你的变量是在哪里初始化的。你很快意识到它来自于

for (List<String> rowData: BankArray)

那么,接下来的问题是BankArray在哪里被初始化。这发生在两个地方。首先是

    static ArrayList<List<String>> BankArray = new ArrayList<>(25); 

你正在创建一个空列表。目前为止还不错。注意,你不需要(也不应该)初始化一个大小。列表不像数组那样,它们可以很容易地增长,你不需要提前给出它们的大小。

第二个地方是

BankArray.add(Arrays.asList(line.split(",")));

这很可能是问题所在。你的row变量包含了Arrays.asList(line.split(","))的结果。因此,该列表的大小取决于你正在读取的字符串中逗号的数量。如果没有逗号,那么大小将为1(字符串本身的值)。这就是我得出你存在数据质量问题的结论所在。

你真正应该做的是在你的for (List<String> rowData: BankArray)循环中添加一个检查。例如,如果你期望有2个字段,你可以写出类似于以下内容:

if (rowData.size() < 2){
throw new Exception("嗯,出了点问题");
}

希望对你有所帮助。

英文:

I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:

        robjs[idx].setAge(Integer.parseInt(rowData.get(1))); 

Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from

for (List&lt;String&gt; rowData: BankArray)

So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all

    static ArrayList&lt;List&lt;String&gt;&gt; BankArray = new ArrayList&lt;&gt;(25); 

You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.

The second place is

BankArray.add(Arrays.asList(line.split(&quot;,&quot;)));

This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(&quot;,&quot;)). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.

What you should really do is add a check in your for (List&lt;String&gt; rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:

if (rowData.size()&lt;2){
throw new Exception(&quot;hmmm there&#39;s been a kerfuffle&#39;);
}

HTH

huangapple
  • 本文由 发表于 2020年10月25日 12:36:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64520396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定