Whenever I run this code, I keep getting an ArrayOutOfBoundException
. I don't know whats wrong, but after looking through it, the error is when I try to convert the string to a number and set it into an array. Any ideas on why and how to fix it?
Sum.txt:
12 2 3 4 5 6 7 8 9 10
90183284 132947132984
1341324245 45 2435 2345 32 6 7 7 578
code:
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;
}