Всякий раз, когда я запускаю этот код, я продолжаю получать ArrayOutOfBoundException
. Я не знаю, что случилось, но, просмотрев его, возникает ошибка, когда я пытаюсь преобразовать строку в число и установить ее в массив. Любые идеи о том, почему и как их исправить?Как найти длину массива для каждой строки?
Sum.txt:
12 2 3 4 5 6 7 8 9 10
90183284 132947132984
1341324245 45 2435 2345 32 6 7 7 578
код:
import java.io.*;
import java.util.*;
public class Sum {
static int lines = 0;
static int arrayvalue = 0;
public static void main(String[] args) {
System.out.println(addnumbers(readFile()));
}
public static int[] readFile() {
String nextline;
int[] inputinarray = new int[25];
try {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner input = new Scanner(new File("sum.txt"));
while (input.hasNext()) {
nextline = input.nextLine();
for (int i = 0; i < inputinarray.length; i++) {
// inputinarray populated as integer array
// ***The error happens here:****
inputinarray[i] = Integer.parseInt(nextline.split(" ")[i]);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
return inputinarray;
}
public static int addnumbers(int[] inputinarray) {
int rowtotal = 0;
for (int i = 0; i < inputinarray.length; i++) {
rowtotal += inputinarray[i];
}
return rowtotal;
}
Подсказка. Отладка этой строки: 'inputinarray [i] = Integer.parseInt (nextline.split (" ") [i]);' –
'nextline.split (" ") [i]' - откуда вы знаете, что результат разделения будет есть, по крайней мере, много элементов? – vaxquis
напечатайте это 'nextline.split (" ") .length', значение будет меньше 25. – YoungHobbit