ArrayIndexOutOfBoundsException double array size
- by Andy
I'm going to preface this question with this statement: I know that I can easily handle this problem by reading the amount of lines in a file and making an array that size. I am not allowed to do this. Anyway, here is my question. I need to double my array's size whenever my program encounters an ArrayIndexOutOfBoundsException and then copy all the previous read in information into the larger array. Here is my code
public static void main(String[] args) throws IOException {
Scanner inScan, fScan = null;
int [] A = new int[5];
inScan = new Scanner(System.in);
System.out.print("Please enter the file to read from: ");
while(true) {
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
break;
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
}
String nextItem;
int nextInt = 0;
int i = 0;
while (fScan.hasNextLine())
{
try
{
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}
catch (NumberFormatException e)
{
System.out.println("Found an invalid int -- ignored");
}
catch (ArrayIndexOutOfBoundsException e)
{
//double the size of array A until
//copy all previous read in information to the larger array
}
}
System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
}