在Java中防止ArrayIndexOutofBoundsException
如何在下面的代码中防止出现在Java中防止ArrayIndexOutofBoundsException,java,indexoutofboundsexception,Java,Indexoutofboundsexception,如何在下面的代码中防止出现ArrayIndexOutofBoundsException,同时转换存储每个记录的标题和值的数据,以便随后准备插入查询 BufferedReader reader = new BufferedReader(new FileReader("C:\\files\\test.dat")); HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<Stri
ArrayIndexOutofBoundsException
,同时转换存储每个记录的标题和值的数据,以便随后准备插入查询
BufferedReader reader = new BufferedReader(new FileReader("C:\\files\\test.dat"));
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
int lineNumber = 1;
String[] columnName = null;
ArrayList<String[]> value = null; // temp array
String line;
String[] arr;
List<String> headers = null;
while (reader.ready())
if (!(line = reader.readLine()).isEmpty()) {
arr = line.split("[\\r\\n]+");
if (lineNumber == 1) {
lineNumber++;
continue;
}
if (lineNumber == 2) {
headers= Arrays.asList(arr[0].split("\\|"));
value=new ArrayList<String[]>();
}
else
value.add(arr[0].split("\\|"));// create values
lineNumber++;
}
// transform data
for (int i = 1; i < headers.size(); i++) {
ArrayList<String> ar = new ArrayList<String>();
for (int j = 0; j < value.size(); j++)
ar.add(value.get(j)[i]); // <---- Getting error here
map.put(headers.get(i), ar);
}
System.out.println(map);
不要假设给定的数组或列表在给定的位置上总是有一些元素。首先检查容器的大小!您希望每一行包含与标题行相同数量的元素。因此,在调用
value.get(j)[i]
之前,请检查value.get(j).length==headers.size()
。如果没有,您可以继续或抛出异常。在哪一行代码上会出现错误?索引越界意味着您的逻辑中有一个错误,您将越过数组的末尾。异常将确切地告诉您发生在哪一行。找出错误并修复。可以使用length()
方法检查数组的长度,以确保访问给定元素是安全的。然后,您需要决定如何处理丢失的数据(例如,跳过该记录、退出或打印错误等)
"X"|"Y"|"12345 0000"
"Emp No"|"Emp sal"|"Emp Name"
1|23.4567|"jhon"
2|0.4567|"steve"
3|9.4567|"jhon"
4|123