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


	}

}

Recommended Answers

All 13 Replies

You have the line number where the error occurred. It looks like you're doing an array read at that line. What is the value of the index you're trying to read at that point?
As Norm would say: put in a println statement before the error to see what the value of the variable is at the time the error occurs. Then backtrack to where the variable got that value.

You have the line number where the error occurred. It looks like you're doing an array read at that line. What is the value of the index you're trying to read at that point?
As Norm would say: put in a println statement before the error to see what the value of the variable is at the time the error occurs. Then backtrack to where the variable got that value.

Thanks for the advice, but I tried so and the print line shows what is normally supposed to show, the array element in its right index position.

I think the problem lies within the variable n, but I just don't know what's wrong.


I think the problem lies within the variable n, but I just don't know what's wrong.

I think you're probably right. What's the value of n there? And more importantly, what's the value of n-1?

I think you're probably right. What's the value of n there? And more importantly, what's the value of n-1?

The value of n there varies depending on what the user has as its input, it is the number of integers the user wishes to enter.

The value of n before at line 86 (where the error) occurs should be the value that the user entered.

n-1 is the last element in the array (as the index positions start with 0, so -1), we want the last element of the series to stay the same as before.

Should be? Have you checked?
If you put in a line like

System.out.println("The value of n entering line 86 is "+n);

I'd be willing to bet that the last thing printed before you hit the exception is
"The value of n entering line 86 is 0"
That's because your exception tells me that you're getting an ArrayOutOfBounds at line 86, trying to access an index of -1. The way you'd get that would be by entering line 86 with n equal to zero.

So, I agree with you that n should be the value entered by the user, so can we assume that this error occurs when the user enters "0" as their input, and not otherwise?
Or are you able to get the error with other inputs?

this code isnt really good:

#
#
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);

your while loop with this code should execute once. In the exception it needs
continue; that way it re-loops at the top and doesn't go down and do your array assignment. Maybe you think the sc.next(); is some sort of continue, it's not. it just grabs whats next in the input. Might be needed to clear \n.

Also watch out for handling only one type of exception. others can be thrown. a general catch all is catch(Exception e) catch the root of the exception class.

Mike

Should be? Have you checked?
If you put in a line like

System.out.println("The value of n entering line 86 is "+n);

I'd be willing to bet that the last thing printed before you hit the exception is
"The value of n entering line 86 is 0"
That's because your exception tells me that you're getting an ArrayOutOfBounds at line 86, trying to access an index of -1. The way you'd get that would be by entering line 86 with n equal to zero.

So, I agree with you that n should be the value entered by the user, so can we assume that this error occurs when the user enters "0" as their input, and not otherwise?
Or are you able to get the error with other inputs?

Yes, I have checked at line 86. I tried different values like 5, and 0. For both it was 5 and 0 respectively.

The error occurs when the user enters "0" as their input, and also for any value that is not an integer, like "g".

just keep in mind the way its written you might as well delete that first do while loop. it goes straight through it. if it hits an exception it still continues on to the array initilization, and then sets your value to escape the loop.

just keep in mind the way its written you might as well delete that first do while loop. it goes straight through it. if it hits an exception it still continues on to the array initilization, and then sets your value to escape the loop.

I am not understanding why it goes straight through do while loop.

Also, if I use the catch all catch(Exception e), is there the need to do the other exceptions? Does this catch all include everything?

Thanks!

Aha. A negative value is probably also going to get you this error as well, right?

This is not really a bug, it's a failure to handle input correctly. You're allowing bad input to get in, and your code doesn't know what to do with it. The program deals correctly with the data it's supposed to deal with, but it doesn't know how to enforce that the data it gets are correct. Where do you think you should fix this?

For the non-integer values, see Mike's post above - you need to change the way you deal with your exception handling.

After it completes the last line of exception code

sc.next();

it continues on the same path as if there had been no exception. it does the array assignment then it assigns your continue loop variable to a value that prompts exit. After a catch, it goes on and does the code it would normally do. the sc.next() does not bump it to loop again. it just grabs what's next in the input stream. you probably want a continue; there so it jumps back to top of loop and tries again.

And yes if you just catch Exception e, you need not catch the rest. sometimes its nice to know what type of exception you have, other times you don't care to code it at that level. you can always print e.stacktrace() i think it is.

Mike

While you're debugging you might try catching (Exception e) ( base class) but word of caution, teachers when teaching exception like to see you catch all the specific exceptions. Maybe a better approach is to catch every exception you can, and i think nextInt() had 3 types. also your next, in the exception block, could generate potentially exceptions of its own.


google java scanner and get the doc on scanner class. search for nextInt and you will see:

Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

Mike

After it completes the last line of exception code

sc.next();

it continues on the same path as if there had been no exception. it does the array assignment then it assigns your continue loop variable to a value that prompts exit. After a catch, it goes on and does the code it would normally do. the sc.next() does not bump it to loop again. it just grabs what's next in the input stream. you probably want a continue; there so it jumps back to top of loop and tries again.

And yes if you just catch Exception e, you need not catch the rest. sometimes its nice to know what type of exception you have, other times you don't care to code it at that level. you can always print e.stacktrace() i think it is.

Mike

Thanks. I think I will make some changes and see if it gets any better.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.