Frage

I'm trying to make a small game like thing for school. It's designed to help you learn your times tables. What I want is for the multiplier of the table to be random each time (5x8 then 5x3 then 5x9 etc).

I've got the generating of the numbers in control with an array as can be seen below

public static Integer[] generateNumbers()
{
    Integer[] arr = new Integer[12];

    for(int j = 0; j < arr.length; j++)
    {
        arr[j] = j+1;
    }
    Collections.shuffle(Arrays.asList(arr));
    System.out.println(Arrays.asList(arr));
    return arr;
}

How can I make it so that every time the user clicks a button, the next number in the array is selected, baring in mind that the button is declared in another class, and the ActionListener is also declared elsewhere?

Oh and the array is available class-wide as the function is declared like this:

public static Integer[] arr = generateNumbers();
War es hilfreich?

Lösung 2

The button int he separate class is not needed, the action listener will communicate with your array whenever its clicked, the easiest way I see is to put a public method int the array's class, that takes an index, which then increments the index, and returns the element stored at it.

Have fun coding, but these assignments are meant for you to scratch your head, try writing some code, and let us know if it breaks, rather than asking for general answers.

Andere Tipps

Thematic answer

public class UnicornFrame extends JFrame {

     private Integer[] poneyArr = MyClassThatGeneratesNumbers.generateNumbers();
     private int poneyCounter = 0;
     private JButton poneyButton;

     public void poneyInit() {
         System.out.println("Unicorns are poney magical friends!");
         poneyButton = new JButton("OMG! Ponies!");
         // Java 8 Lambdas! Yey!
         poneyButton.addActionListener(e -> { 
             if (poneyCounter >= poneyArr.length) {
                  poneyArray = MyClassThatGeneratesNumbers.generateNumbers();
                  poneyCounter = 0;      
             }         
             Integer selected = poneyArr[poneyCounter++];   
             System.out.println("OMG! I have selected " + selected);
         });

         // other stuff

         add(poneyButton, BorderLayout.CENTER);
     }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top