This site requires JavaScript, please enable it in your browser!
Greenfoot back
meadwho
meadwho wrote ...

2015/9/3

Get Random Number with no repeats

meadwho meadwho

2015/9/3

#
I'm new to Greenfoot
   
int[] userAnswer;
Array is declared as a global variable
 public void levelOne()
    {
        do{
            tableSelection = JOptionPane.showInputDialog("Select the multiplication table you wish to practice \nBetween 1 - 12");
            timesTable = Integer.parseInt(tableSelection);
        }while(timesTable <=0 || timesTable >=13);
        
        for(int i =0;i<11;i++) {
            userAnswer = new int[10];
            questionNumber = Greenfoot.getRandomNumber(12);
            question = JOptionPane.showInputDialog(timesTable + " x " + questionNumber + " = ?" );
            userAnswer[i] = Integer.parseInt(question);
        }
        
        for(int i=0;i<11;i++) {
            System.out.println(userAnswer[i]);
        }
    }
}
the program should not repeat the same question 1x2 and 2x1 is not the same and also i can't seem to store the answer in the array. this is the error i get java.lang.ArrayIndexOutOfBoundsException: 10
danpost danpost

2015/9/3

#
Your 'userAnswer' array is declared as a ten element array (indexed from zero to nine), but your 'for' loop counter, 'i', will increment to ten (which is outside the index range of the array). Line 12 will fail when 'i' reaches the value of ten. Change the 'for' loops on lines 8 and 15 to the following:
for (int i=0; i<10; i++) {
You need to login to post a reply.