[英]ArrayIndexOutOfBound when parsing int from string array
I am new to StackExchange so I will do my best at making this question as understable as possible. 我是StackExchange的新手,所以我会尽力使这个问题变得尽可能明智。 I am trying to take all Integers from a String Array created from a .csv file.
我试图从一个.csv文件创建的字符串数组中获取所有整数。 The file looks like so,
该文件看起来像这样,
and so on... 等等...
Everything works perfectly until I try to add the numbers to the array. 一切都很完美,直到我尝试将数字添加到数组。 The output returns a ArrayIndexOutOfBoundsException.
输出返回ArrayIndexOutOfBoundsException。 I made the MAX_SIZE of this array = 100. The amount of integers in the text file is no more than 8. I don't understand why this is problem is happening.
我使这个数组的MAX_SIZE = 100.文本文件中的整数数量不超过8.我不明白为什么会出现问题。 Are my for-loops completely wrong or is there more to the problem?
我的for循环是完全错误还是更多问题?
public static void loadNums()
{
String inputFile=("/Users/user1/Desktop/list.csv");
File file = new File(inputFile);
Scanner scanFile = null;
try{
scanFile =new Scanner(file);
}catch(NumberFormatException | FileNotFoundException exception){
System.out.println("Error");
}
if (scanFile != null)
{
String[] numStrs = scanFile.nextLine().split(",");
int[] num = new int[numStrs.length];
for (int i =0; i <numStrs.length; i++)
{
if (i ==0)
{
System.out.println("Numbers");
}
else
{
numStrs = scanFile.nextLine().split("\\d+.,\\d+");
for (int j =0; j <numStrs.length; j++)
{
num[i] = Integer.parseInt(numStrs[i]);
}
System.out.println(num[i]);
}
}
}
You try to parse the second array numStrs
with the first index i : 您尝试使用第一个索引i解析第二个数组
numStrs
:
num[i] = Integer.parseInt(numStrs[i]);
So instead to that use this, change the numStrs[i]
with numStrs[j]
: 所以相反,使用它,用
numStrs[j]
更改numStrs[i]
numStrs[j]
:
num[i] = Integer.parseInt(numStrs[j]);
Hope this can help you. 希望这可以帮到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.