-3
//row 0 are questions and row 1 are answers

public String[][] correctAnswers = {
    {"What name was on the door the day he ran away?"},
    {"Mike Smith"}
};

public String[] wrongAnswers = new String[]{"Rory Mcilroy", "Bob Jones", "Arnold Palmer"};

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    Log.d("new game","onCreate");

    setContentView(R.layout.game_layout);

    //Get three random indexes for the wrong answers here   
    //Get the three wrong answers for buttons

    String[] afb = new String[3];
    for(int i = 0;i<4;i++){
        Random rnd = new Random();
        int a = rnd.nextInt(2);
        System.arraycopy(wrongAnswers, a, afb, i, wrongAnswers.length);
    }
}
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48

2 Answers2

1

Look that you have i<4 in your loop. And you just have 3 positions in your array. You have to remember that arrays start on position 0, not 1.

If you look at Java documentation you can see what happens:

Copies an array from the specified source array

You are copying the wrongAnswers array.

beginning at the specified position

Your a variable could be 0 or 1.

to the specified position of the destination array

If your i variable it's 4 then it couldn't get any value from wrongAnswers array and it will crash with an ArrayIndexOutOfBoundsException.

What can you try it's to put your System.arraycopy without the for loop. Like this:

System.arraycopy(wrongAnswers, 0, afb, wrongAnswer.length - 1, wrongAnswers.length);

I really don't understand why do you need a random number to do this (look that with System.arraycopy you can copy all the array in one time).

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
0

If you want to get all the non-repeated indexes in random order, you may consider to copy the entire array and then shuffle it.

private static void shuffle(String[] ar){
  Random rnd = new Random();
  for (int i = ar.length - 1; i > 0; --i) {
    int index = rnd.nextInt(i + 1);
    String s = ar[index];
    ar[index] = ar[i];
    ar[i] = s;
  }
}

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    Log.d("new game","onCreate");

    setContentView(R.layout.game_layout);

    //Get three random indexes for the wrong answers here   
    //Get the three wrong answers for buttons

    String[] afb = new String[3];       
    System.arraycopy(wrongAnswers, 0, afb, 0, afb.length);

    //prints the original array
    for(int i=0; i<afb.length; ++i)
        System.out.println(afb[i]);

    shuffle(afb);

    //prints the shuffled array
    for(int i=0; i<afb.length; ++i)
        System.out.println(afb[i]);
}

The above private static void shuffle(String[] ar) is an edit from the method found in this answer provided by the user PhiLho.

Community
  • 1
  • 1
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48