Hello

I'm trying to make a random number generator to work out probability and chance, although it keeps coming up with an ArrayIndexOutOfBoundsException on line 41(roughly).

I would be really greatful if you could help!

thx

p.s.This is not for school

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package randomiser;
import javax.swing.*;
/**
 *
 * @author Toby
 */
public class Main extends JFrame{

    public Main(){
        super("Randomizer");
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String x = JOptionPane.showInputDialog("How many possablilities:");
        String y = JOptionPane.showInputDialog("How many tries");
        int poss = Integer.parseInt(x);
        int times = Integer.parseInt(y);


          int[] results = new int[poss];

for(int i = 0; i < poss; i++){
        results[i] = 0;
}


String[] comps = new String[poss];
        for(int i = 0; i < times; i++){
            int result = (int)(Math.random()*poss);
            int z = results[result];
            z++;
        }

        
        
 for(int z = 0; z <= poss ;z++){
     String whatever = z + " : " + results[z];
            comps[z] = whatever;
        }

       

        JList list = new JList(comps);
        JPanel pane = new JPanel();
        JScrollPane scroll = new JScrollPane(list);
       
        pane.add(scroll);
        add(pane);
        setVisible(true);


    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Main x = new Main();// TODO code application logic here
    }

}

Recommended Answers

All 3 Replies

I noticed that in line 24

int[] results = new int[poss];

you create an array results with size poss.

then in line 40

for(int z = 0; z <= poss ;z++){     String whatever = z + " : " + results[z];            comps[z] = whatever;        }

For example, poss = 2, results will be

result[0]
result[1]

Notice that although you create an array of size 2, the array index is only up to 1 because index starts at zero.

Then in line 40, you do a for loop from 0 to 2, but since results[2] is not there, it gives you the ArrayOutOfBounds exception.

Try coding your for loop as

for (int i = 0; i < poss; i++) {}

Thank you so much, hopefully it works!!!!:)

I'm a stickler for spelling and grammar ;-) You may want to change "How many possablilities" to be "How many possibilities" (you've misspelt it!)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.