Muhammad Talal Muhammad Talal - 25 days ago 11
Java Question

Set random text with multidimensional array

I'm trying to setText to a textView with multidimensional array with random number. It works fine but only once. How can i make it so that with each button click the text changes itself again and again. Here is my code (I cut it a bit to keep it simple):

public class MainActivity extends Activity implements View.OnClickListener{
String quiz[][];
int ques;
int ans;
Random myRand = new Random();
int myInt = myRand.nextInt(10);


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

quiz = new String[3][2];

quiz[0][0] = "Q:1";
quiz[0][1] = "A:1";

quiz[1][0] = "Q:2";
quiz[1][1] = "A:2";

quiz[2][0] = "Q:3";
quiz[2][1] = "A:3";



ques = 0;
ans = 1;

button4 = (Button)findViewById(R.id.button4);
button4.setOnClickListener(this);

textView2 = (TextView)findViewById(R.id.textView2);
textView3 = (TextView)findViewById(R.id.textView3);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button4:
textView2.setText(quiz[myInt][ques]);
textView3.setText(quiz[myInt][ans]);
break;
}
}

Answer

Its simple, you should make new random in onClick event

    @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button4:
                myInt = myRand.nextInt(10);
                textView2.setText(quiz[myInt][ques]);
                textView3.setText(quiz[myInt][ans]);
            break;
}
Comments