代码相当简单,但我不明白为什么会出现此错误。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
String fileName = "States.csv";
File file = new File(fileName);
try {
Scanner stream = new Scanner(file); // or use new File();
while (stream.hasNext()){
String data = stream.next();
String[] values = data.split(",");
System.out.println(values[3] + "***");
}
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
system.out.println(values[3] - "***")
可能有问题,我看了看,但没有运气。
最佳答案
因为数组
的大小可能小于4
,并且您正在尝试打印第4
元素(索引3
)
在打印之前检查您的数组
长度:
try {
Scanner stream = new Scanner(file); // or use new File();
while (stream.hasNext()){
String data = stream.next();
String[] values = data.split(",");
if(values.length>3){
System.out.println(values[3] + "***");
}
else{
System.out.println("Desired value is missing in this row");
}
}
}
关于java - 数组索引越界,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21346309/