ArrayIndexOutOfBoundsException double array size
Posted
by
Andy
on Stack Overflow
See other posts from Stack Overflow
or by Andy
Published on 2012-11-26T04:56:33Z
Indexed on
2012/11/26
5:03 UTC
Read the original article
Hit count: 120
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] + " ");
}
}
}
© Stack Overflow or respective owner