-1

I would like to create an alarm where user have to play in mini game to turn off the sound. So minigame should rand 1 from 0 to 100 which should be picked from 9 buttons with numbers. And this should happen 10 times. If the user click bad button, then it should start again 10 times. In every iteration I would like to change number to select, and numbers on buttons.

To do this I created an array from buttons:

Button[] buttons = {
            button1,
            button2,
            button3,
            button4,
            button5,
            button6,
            button7,
            button8,
            button9
    };
    private int i = 0;

And on onCreateView I am trying to assign values to this buttons:

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_numbers_game, container, false);

    buttons[0] = view.findViewById(R.id.button1);
    buttons[1] = view.findViewById(R.id.button2);
    buttons[2] = view.findViewById(R.id.button3);
    buttons[3] = view.findViewById(R.id.button4);
    buttons[4] = view.findViewById(R.id.button5);
    buttons[5] = view.findViewById(R.id.button6);
    buttons[6] = view.findViewById(R.id.button7);
    buttons[7] = view.findViewById(R.id.button8);
    buttons[8] = view.findViewById(R.id.button9);
    randomNumber = view.findViewById(R.id.randomNumber);

    displayNumbers();//assign values at the start
    for (i=0;i<9;i++){
        buttons[i].setOnClickListener(v -> {
            if (Integer.parseInt(buttons[i].getText().toString()) == intRandomNumber) {//sometimes I get there ArrayIndexOutOfBoundsException
                winIterator++;
                Log.d("numbersGame", "correct " + intRandomNumber);
                Toast.makeText(getActivity(), R.string.correctAnswer, Toast.LENGTH_SHORT).show();
                if (winIterator == 10) {
                    Bundle result = new Bundle();
                    result.putBoolean("isFinished", true);
                    getParentFragmentManager().setFragmentResult("requestKey", result);
                }
            } else {
                winIterator = 0;
                Log.d("numbersGame", "incorrect " + intRandomNumber);
                Toast.makeText(getActivity(), R.string.incorrectAnswer, Toast.LENGTH_SHORT).show();
            }
            displayNumbers();
        });
    }

    return view;
}

randomNumber is a textView to display random number. I am trying to attach for every button listener that if the text in this button will equals random number, then counter will increase by 1. And if the counter equal 10, then it will turn off the alarm. In other case it should assign 0 to winiterator. And for every clicked at the end, display numbers to assign new values to buttons, this function is below.

public void displayNumbers() {

    intRandomNumber = random.nextInt(100) + 1;//number which should be selected
    randomNumberButtonIndex = random.nextInt(9);//index number in buttons

    String stringRandomNumber = String.valueOf(intRandomNumber) + "";
    randomNumber.setText(stringRandomNumber);

    buttons[randomNumberButtonIndex].setText(stringRandomNumber);
    for (int i = 0; i < 9; i++) {
        if (i == randomNumberButtonIndex) {
            continue;
        }
        do {
            randomOtherNumber = random.nextInt(100) + 1;
        } while (randomOtherNumber == intRandomNumber);
        buttons[i].setText(Integer.toString(randomOtherNumber));//random and assign other values
    }

}

Sometimes I get in the described place:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.budzikinteraktywny, PID: 9319
java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
    at com.example.budzikinteraktywny.NumbersGameFragment.lambda$onCreateView$0$com-example-budzikinteraktywny-NumbersGameFragment(NumbersGameFragment.java:89)
    at com.example.budzikinteraktywny.NumbersGameFragment$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
    at android.view.View.performClick(View.java:7870)
    at android.widget.TextView.performClick(TextView.java:14970)
    at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
    at android.view.View.performClickInternal(View.java:7839)
    at android.view.View.access$3600(View.java:886)
    at android.view.View$PerformClick.run(View.java:29363)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7948)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)

But checked a lot of times and I cant see this place where something gone wrong. Any help is appreciated. Thank you

Pedro532
  • 47
  • 4

1 Answers1

0

Since you hold your i parameter as a class member and incrementing it in the for loop, The last value it is set to is 9 (and then the loop condition is false (i < 9).

When the onClick occurs, you are calling:

Integer.parseInt(buttons[i].getText().toString());

Then you are out of bounds, because:

buttons[9]

Is incorrect.

Try to use this:

for (i=0;i<9;i++){
    final Button button = buttons[i];
    button.setOnClickListener(v -> {
        if (Integer.parseInt(button.getText().toString()) == intRandomNumber) {

         .. The rest of your code 

        }
    }
}
gioravered
  • 1,758
  • 3
  • 19
  • 30