I'm somewhat new to Java and programming in general and I am receiving this error when I run my program and I have zero idea as to what is causing it. Thanks in advance.

public class AssignmentEight 
{
	static final String INFILE_NAME = "ass8_input.txt";	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		Scanner inFile = null;
		
		try
		{
			inFile = new Scanner(new File(INFILE_NAME));
		}
		catch(FileNotFoundException e)
		{
			System.out.println("Error: " + e.getMessage());
			System.exit(1);
		}
		
		int count = inFile.nextInt();
		double checkSum = 0;
				
		for(int ii = 0; ii < count; ++ii)
		{
			int[] numbers = new int[ii];
			numbers[ii] = inFile.nextInt();
			System.out.println(numbers[ii]);
		}
		
	}

}

Recommended Answers

All 5 Replies

The problem is that you are setting the array length =ii at line 26 and accessing the value on ii at line 27 which is wrong the last index of array will be ii-1. Another problem is at first iteration you are setting the length =0 and accessing the array index these are causing the problems.
Why are you using this loop?

for(int ii = 0; ii < count; ++ii)
		{
			int[] numbers = new int[ii];
			numbers[ii] = inFile.nextInt();
			System.out.println(numbers[ii]);
		}

or you can add 1 to the value of count in your loop

or you can add 1 to the value of count in your loop

what good would that do? he would still be trying to fill a non-existing spot in an array.

I think what you want is more something like:

...
int [] numbers = new int[count];
for(int ii = 0; ii < count; ++ii)
{
numbers[ii] = inFile.nextInt();
System.out.println(numbers[ii]);
}
...

basically, you create the array before the iteration, and you don't create a new one each time your iteration runs. there's no need to do this anyway, since count is known before you go in the loop.
you just fill in the correct element each time.

so, don't go messing with count, but just check the answer given to you by abelLazm and take a look at the little code snippet I've written here. that should help you out just fine.

Solution is simple

int[] numbers = new int[ii+1];

again: no need to revive dead threads.

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.