For my Java homework I had to make a program that simulates 100,000 people going 25 times around a monopoly board and finding the percentage times a space is landing on. I get this error when I run it.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 39
at Monopoly.analyze(Monopoly.java:86)
at TestMonopoly.main(TestMonopoly.java:6)
Here is my main code.
public class Monopoly
{
String[] names = new String[39];
Dice roller = new Dice();
final int numPlayers = 100000;
final int timesAround = 25;
public void setUpBoard()
{
names[0] = "Go";
names[1] = "Mediterranean Avenue";
names[2] = "Community Chest";
names[3] = "Baltic Avenue";
names[4] = "Income Tax";
names[5] = "Reading Railroad";
names[6] = "Oriental Avenue";
names[7] = "Chance";
names[8] = "Vermont Avenue";
names[9] = "Connecticut Avenue";
names[10] = "In Jail/Just Visiting";
names[11] = "St. Charles Place";
names[12] = "Electric Company";
names[13] = "States Avenue";
names[14] = "Virginia Avenue";
names[15] = "Pennsylvania Railroad";
names[16] = "St. James Place";
names[17] = "Community Chest(2)";
names[18] = "Tennessee Avenue";
names[19] = "New York Avenue";
names[20] = "Free Parking";
names[21] = "Kentucky Avenue";
names[22] = "Chance(2)";
names[23] = "Indiana Avenue";
names[24] = "Illinois Avenue";
names[25] = "B&O Railroad";
names[26] = "Atlantic Avenue";
names[27] = "Ventnor Avenue";
names[28] = "Water Works";
names[29] = "Marvin Gardens";
names[30] = "Go to Jail";
names[31] = "Pacific Avenue";
names[32] = "North Carolina Avenue";
names[33] = "Community Chest(3)";
names[34] = "Pennsylvania Avenue";
names[35] = "Short Line";
names[36] = "Chance(3)";
names[37] = "Park Place";
names[38] = "Luxury Tax";
names[39] = "Boardwalk";
}
public double[] analyze()
{
int[] visits = new int[39];
for(int i = numPlayers; i < 0; i--)
{
int currentPosition = 0;
int aroundBoard = 1;
for(int j = timesAround; j > 0; j--)
{
Dice rolling = new Dice();
int number = rolling.roll2Dice();
currentPosition += number;
visits[currentPosition]++;
if(currentPosition == 30)
{
aroundBoard++;
currentPosition = 10;
}
if(currentPosition > 39)
{
aroundBoard++;
currentPosition -= 40;
}
}
}
double[] percentages = new double[39];
int totalMoves = 0;
for(int i = 0; i < 40; i++)
{
totalMoves = totalMoves + visits[i];
}
for(int i = 0; i < 40; i++)
{
percentages[i] = (visits[i] / totalMoves) * 100;
}
return percentages;
}
public void printResults(double percents[])
{
System.out.println("Results of Test:");
System.out.println("");
for(int i = 0; i < 40; i++)
{
System.out.format(names[i] + "%.2f%n", percents[i]);
}
}
}
If you need to see my dice class or my test class, please ask. Any help?