Hi there,

I have to create a card game as an assignment, and i am having trouble with a part of the assignment.

Basically, there is an array, 'playerHand', which holds a set of integers. What i want to do is to add the elements of the array and then assign it an integer.

Here's what i have so far:

public static int scoreCalculator (int [] array, int howManyToAdd){ //user passes an array and the number of the index to which to add to. this method calculates the score
		int score = 0; // the integer which holds the score
		
		for (int count = 0; count <= howManyToAdd; count ++) //loops through each 
			score = score + array [count];
		return score;
	}

This is the error I am getting:

Caused by: java.lang.ArrayIndexOutOfBoundsException: 2

Thanks in advance :)

Recommended Answers

All 4 Replies

You're trying to access the third element of array[] and it doesn't have that many elements. Don't do that.

I think i may have isolated the problem.

Will the following code create an array with 3 null spaces?

int arraySize = 2;
int [] hand = new int [arraySize];

EDIT:
@Ezzaral, sry i didn't see your post. But i dont think the problem is what you said because if the above code works, then a new array with 3 elements should be created.

EDIT:
@Ezzaral, OMG it worked!! idk how but i increased the arraySize by 1. Logically it makes no sense, because the index starts at 0. Mind explaining it for me?

An array of size 2 will mean you can store 2 objects. I am not sure why you think it is 3.

So, An array which holds 2 objects will looke like this:
array[0] = object 1
array[1] = object 2

So, when you create an array of size N. The last index in that array will be N-1

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.