Can't Fix Array Out of Bounds
Hey guys I made this program that counts the number of times a face value on a die is rolled, based on the user input, but i keep getting a out of bounds exception; HELP :(
Code Java:
import java.util.Scanner;
import java.util.Random;
public class CountDiceRolls
{
public static void main(String[] args)
{
int numberOfDieRolls = rollADie();
faceValueOfDie(numberOfDieRolls);
}
public static int rollADie()
{
Scanner input = new Scanner(System.in);
System.out.print("How Many Times Would You Like To Roll A Die: ");
int num = input.nextInt();
return num;
}
public static void faceValueOfDie(int numberOfDieRolls)
{
Random random = new Random();
int [] faceVal = new int [numberOfDieRolls];
for(int count = 0; count < numberOfDieRolls; count++)
{
int face = 1 + random.nextInt(6);
faceVal[face]++;
}
display(faceVal);
}
public static void display(int [] faceVal)
{
System.out.print("Face\tTimes\n");
for(int counter = 1; counter <= 6; counter++)
{
System.out.println(" " + counter + "\t\t " + faceVal[counter]);
}
}
}
Re: Can\'t Fix Array Out of Bounds
Which line is giving your the error?
How many indices does your array have? Print it out to be sure.
Which index are you trying to access? Print it out to be sure.
Also, don\'t forget the highlight tags when posting code.
Re: Can\'t Fix Array Out of Bounds
Re: Can't Fix Array Out of Bounds
Thank you very much, helped alot I figured out that I was incrementing it at the wrong time, had to go back and see which operations run in what order so the solution was getting rid of my "face" variable and just making a random number in the array and I had to switch the (++) increment operator from the back to the front and it worked :)
Re: Can't Fix Array Out of Bounds
Hi,
I think you need to change your code.
for <<<
public static void faceValueOfDie(int numberOfDieRolls)
{
Random random = new Random();
int [] faceVal = new int [numberOfDieRolls];
for(int count = 0; count < numberOfDieRolls; count++)
{
int face = 1 + random.nextInt(6);
faceVal[face]++;
}
display(faceVal);
}
>>>
user faceVal[count] to store like faceVal[count]=face;
bean factory
Re: Can't Fix Array Out of Bounds