0

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 :)

Edited by marvolo1300: n/a

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by marvolo1300
Featured Replies
  • 1
    Ezzaral 2,714   5 Years Ago

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

1

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

0

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?

Edited by marvolo1300: n/a

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.