这是我的字符串:
String csvFile = "Screenname,Firstname,Email,Timezone,Organization,Password,Lastname,Middlename,Gender,Birthdate\n"
+ "Test01,Test01,test01@.khalibre.com,GMT+8,Khalibre,12345,test,test,M,3/8/1980\n"
+ "Sok Dara,Dara,test02@khalibre.com,GMT-7,Khalibre,12345,Sok,Dara,,1980-d1-25\n"
+ "Test03,,test03@khalibre.com.kh,GMT+1,Khalibre,12345,test,test,M,2/2/1980\n"
+ ",Test04,test04@khalibre.com,GTM-8:00,Khalibre,12345,test,test,F,\n";
这个主要方法:
boolean firstLine = true;
String[] readLineCSVs = csvFile.split("\n");
for (String readLineCSV : readLineCSVs) {
rows++;
if (firstLine) {
firstLine = false;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Readdata rd = new Readdata();
String[] csvData = readLineCSV.split(csvSplitBy);
int count =0;
while(csvData[count++]!=null){
System.out.println(count);
}
System.out.println(csvData[0]);
System.out.println(csvData[1]);
System.out.println(csvData[2]);
System.out.println(csvData[3]);
System.out.println(csvData[4]);
System.out.println(csvData[5]);
System.out.println(csvData[6]);
System.out.println(csvData[7]);
System.out.println(csvData[8]);
System.out.println(csvData[9]);
}
错误显示如下:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at demo002.D2_F_003.readData(D2_F_003.java:38)
at demo002.D2_F_003.main(D2_F_003.java:247)
如何抛出此异常?
答案 0 :(得分:0)
boolean firstLine = true;
String[] readLineCSVs = csvFile.split("\n");
for (String readLineCSV : readLineCSVs) {
rows++;
if (firstLine) {
firstLine = false;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Readdata rd = new Readdata();
String[] csvData = readLineCSV.split(csvSplitBy);
int count =0;
try{
while(csvData[count++]!=null){
System.out.println(count);
}
System.out.println(csvData[0]);
System.out.println(csvData[1]);
System.out.println(csvData[2]);
System.out.println(csvData[3]);
System.out.println(csvData[4]);
System.out.println(csvData[5]);
System.out.println(csvData[6]);
System.out.println(csvData[7]);
System.out.println(csvData[8]);
System.out.println(csvData[9]);
}
catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
答案 1 :(得分:0)
try{
//Your Code
}catch(ArrayIndexOutOfBoundsException ex){
//If error show
}
catch(Exception e){
}
答案 2 :(得分:0)
如果您要求如何解决错误,这看起来非常可疑:
int count =0;
while(csvData[count++]!=null){
System.out.println(count);
}
我不确定null检查应该是什么。 String的split方法不会返回带有null元素的数组。
从异常消息(ArrayIndexOutOfBounds 10)判断,您的数组只有10个元素,但您尝试访问索引10(记住数组索引从0到长度 - 1)。您需要限制计数,以使其不会超过最后一个索引。
这至少会阻止异常:
int count = 0;
while(count < csvData.length && csvData[count++] != null) {
System.out.println(count);
}