0

The code i am working with is below.

    for(int i = 0; i < playerCount; i++)
    {
        j=0;
        System.out.println(playerNames[i] + "'s turn!");

        while(userChoice != 2 && j < 5) 
        {
            Die roll2 = new Die();
            roll2.roll();
            System.out.println(roll2);

            diceArray[i][j] = roll2;

            System.out.println("Again? 1= yes, 2=no");
            userChoice = scan.nextInt();
            j++;

        }

        if(userChoice == 2)
        {
            userChoice = 1;


        }


    }

And i am wondering, How could i add a counter, to see how many values are in each row of the array, this is a 2D array, which will have an unknown number of rows, and less than 5 columns. (It could be 5, could be 1.). I cannot do this with a simple count++ because of the multiple rows.

Anyone have any tips?

4
  • 1
    diceArray.length will return the number of rows in the array and diceArray[0].length will return the number of columns (number of values associated with each row) which i believe is what you are looking for. Commented Nov 30, 2015 at 3:20
  • So if i wanted to save those values, I could do like int arrayLength = diceArray.length? Commented Nov 30, 2015 at 3:20
  • @3kings is correct, although just using playerCount for the rows will save you the negligible amount of time calling diceArray.length will take. Commented Nov 30, 2015 at 3:22
  • @JonRoy Yeah. arrayLength would then be the value of how many int[] Commented Nov 30, 2015 at 3:22

1 Answer 1

1

You can get the number of columns for a row in a 2D array using array[i].length. For example:

for(int row=0; row < array.length; row++) {
    System.out.println("Num Of Col for row " + row + ": " + array[row].length);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is there any way i could get this to disregard the entries that are null? I had to set a column value over 0, so i could initialize the 2D array?
@JonRoy in Java the default values for an array entries that are of type int is 0. If you want to modify the values (different than zero), you will need to write a nested loop that goes from col = 0 to array[row].length, and modify the value array[row][col] = NEW_INT

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.