0

Please bear with me here, I had hospital appointments this week and unfortunately I have NO idea how to use 2D arrays, and barley know arrays for that matter. I am trying to figure them out though. I am running this code below as a test for my project and am getting the following error

How many players? 2
What is your name: alan
What is your name: joseph
Exception in thread "main" 27
alan's Turn! 
java.lang.ArrayIndexOutOfBoundsException: 0
at ASgn8.main(ASgn8.java:41)

My code is Below

import java.util.Arrays;
import java.util.Scanner;

class ASgn8 {

public static void main(String[] args)
{

    Die[][] myDie = new Die[0][0];

    Scanner scan = new Scanner(System.in);

    System.out.print("How many players? ");
    int playerCount = scan.nextInt();
    scan.nextLine();

    String[] playerNames = new String[playerCount];

    for(int i = 0; i < playerCount; i++)
    {
        System.out.print("What is your name: ");
        playerNames[i] = scan.nextLine();

    }

    int again = 1;

    int randomNum = (int)(Math.random() * (30-10)) +10;
    System.out.println(randomNum);


    Die firstRoll = new Die();

    for(int j = 0; j < 5; j++)
    {

        System.out.println(playerNames[j] + "'s Turn! ");

            firstRoll.roll();

            myDie[j][0] = firstRoll;


    }





    }

}

It highlights the following when i click the error

myDie[j][0] = firstRoll;
Jon Roy
  • 53
  • 1
  • 11

1 Answers1

1

Your array Die[][] myDie = new Die[0][0]; is of size zero by zero. Any attempt to access it will be out of bounds.

Try initializing it to some none zero dimensions e.g. Die[][] myDie = new Die[10][10]; would give you a 10*10 2d array.

bhspencer
  • 13,086
  • 5
  • 35
  • 44
  • Alright! Thanks man! Makes sense! – Jon Roy Nov 28 '15 at 01:21
  • After i changed the values, it now gives me an out of bounds error on the System.out.println(playerNames[j] + "'s Turn! "); Line – Jon Roy Nov 28 '15 at 02:03
  • well what is the value of `j` at this point and what is the size of the array `playerNames`? – bhspencer Nov 28 '15 at 02:03
  • You cannot try an access an element of an array that is greater than the size of the array. – bhspencer Nov 28 '15 at 02:04
  • The value of j is 0, the size of the array is 2, This would cause problems right? sorry man i just draw a complete blank on arrays. – Jon Roy Nov 28 '15 at 02:04
  • j being zero is fine for an array of size 2. The problem is that you initialize the array to size `playerCount` but then you loop j from 0 to 5. If 5 is greater than `playerCount` you will get an IndexOutOfBounds exception. Try changing your loop to `for(int j = 0; j < playerCount; j++)` – bhspencer Nov 28 '15 at 02:07
  • At this point I think it is probably best if you follow some tutorials on arrays in Java until you have a clearer understanding of how to use them. – bhspencer Nov 28 '15 at 02:09