Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am am in desperate need of java array help! The user enters how many dice to u

ID: 3626195 • Letter: I

Question

I am am in desperate need of java array help! The user enters how many dice to uses and the second input is how many rolls. I am confused with the array concept and I need help understanding! I am not asking anyone to do my hw but to guide and help me understand. this is all i have so far.
import java.util.*;

public class RollDice
{
public static void main(String [] args)
{
Scanner input= new Scanner(System.in);
//int []n;
int dice=0,rolls=0;
System.out.println("Enter the number of dice you wish to use");
dice=input.nextInt();
System.out.println();
int[]n=new int[dice];

System.out.println("Enter the number of dice you wish to use");
rolls=input.nextInt();
System.out.println();
int[]r=new int[rolls];

for(int i=0;i<dice;i++)
}
}

Explanation / Answer

Ok, I'm going to assume that you know absolutely nothing about arrays. (It's much easier to start with this assumption). Arrays are containers for data. For example, let's say that you wanted to store the ages of all of your friends. Before arrays, all you could do would be to declare that many integer variables (called ageOne, ageTwo, etc...) and manually read them in (like ageOne = input.nextInt(); ageTwo = input.nextInt(); etc...). This might not sound like a problem, but what if you had 1,000 friends! Or even 10,000!

This is where arrays can help. Arrays not only provide one name to access all of the data, it's very easy with and easy to update. Going back to our previous example, we can int[]friendAge = new int[10000]. We know have storage for 10,000 integers into the friendAge array. But how do we accesss the data? When you declared and sized the array, the computer takes up 10,000 slots for ints in the memory. We denote these slots by the array name, followed by [, and index number, and then ].

For example, let's say that we wanted access to the first element in the array. We would use friendAge[0]. The most common mistake that new programmers make is forgetting that array indecies start at 0, not 1.

In the program that you have submitted, you have the beginning of a for loop for the dice. Let's explore this for a bit. Obviously, the for loop is fine, but what do we put inside of it? If you're wanting to read in the value for the dice, we can use the bracket notation mentioned before.

for (int i = 0; i < dice; i++) {

     rolls[i] = input.nextInt();

}

As the loop goes through, we are incrementing where we are accessing the data. As you could imagine, printing out is just as easy.

I hope this answers your questions. Please let me know if you have others.

Good Luck,

Cameron