mercredi 9 septembre 2020

Android: switch case & random number code in the case

Trying to code by my own, I am facing an issue which I do not understand from the compiler statements. Basically, when you click a radio button, a random number is generated in the textview field. My problem is that the random code written in the case of the clicked radio button is not accepted by the compiler.

Here is the code:

package com.example.random;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();
        TextView MytextView = (TextView)findViewById(R.id.MytextView);
        int random;
        int random2;

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.radioButton01:
                if (checked)
                    // 0 or 1 code
                    random = getRandomNumber(0,1);
                    MytextView.setText(random.toString());
                    break;
            case R.id.radioButton1to6:
                if (checked)
                    // 1 to 6 code
                    random2 = getRandomNumber(1,6);
                    MytextView.setText(random2.toString());
                    break;
        }
    }

    private int getRandomNumber(int min,int max) {
        return (new Random()).nextInt((max - min) + 1) + min;
    }

}

I presume that the 2 lines 'Int random;' are wrong, but the compiler seems to want to have them here. I would have understood that the line 'random = getRandomNumber(0,1);' would have be sufficient in the case part of the code, but the compiler marks 'random' in red.

I would like to understand what I am missing here. Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire