I am writing a program for class on catching exceptions. Everything compiles fine, but when I try to test my error trapping, this shows up.
"How many integers would you like to enter? f
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
This is not a correct integer, please try again.
Before:
After: at Array.main(Array.java:86)"
The below is my program. Thanks!
/**
*This program will let the user choose to enter a desired amount of integers.
*Each integer will then be changed and displayed to be the sum of itself and
*the next integer. The last integer will not be changed. Sept 11, 2010
*
* @author
**/
import java.io.*;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Array {
/**
* The main method will obtain the user input using standard I/O, then
* storing the user input in an array. The array will then be altered
* to display a new list of integers.
* @param args
* Unused
**/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int n=0, i, order; //n will store the user input for the number of integers
//i will serve the purpose of a counter
int [] x;
//The line below creates a reference to a new Scanner object
// called "sc". It reads lines from standard input one at a time.
Scanner sc = new Scanner (System.in);
boolean checkException = false;
do {
System.out.print ("How many integers would you like to enter? ");
try {
n = sc.nextInt(); // stores the next integer typed by the user in n using Scanner sc
}
catch (InputMismatchException e)
{
System.out.println("This is not a correct integer, please try again.");
sc.next();
}
x = new int[n]; //declares the array variable x, giving x n elements
checkException = true;
} while (checkException == false);
checkException = false;
for (i=0; i<x.length; i++)
{
order = i + 1;
do {
System.out.println("Please enter your integer number "+order);
try {
x[i]= sc.nextInt();//stores the user inputs into the indexed array elements
checkException = true;
}
catch (InputMismatchException e)
{
System.out.println("This is not a correct integer, please try again.");
sc.next();
}
} while (checkException == false);
}
System.out.println("\nBefore: ");
for (i=0; i<x.length; i++)
{
System.out.print(x[i]+"\t"); //print out the user inputted array
}
System.out.print("After: ");
for (i=0; i<n-1; i++) //make changes to all the integers except for the last one
{
x[i]=x[i]+x[i+1]; //add the integer to the next integer to obtain the new array
System.out.print(x[i]+"\t"); //print out the changed integers
}
System.out.print(x[n-1]); //print the last unchanged integer
}
}