jeudi 25 juin 2015

How can I use a value of a variable that is assigned to the variable in a previous if statement?

This is code in Android Studio. I created Buttons start, higher and lower. The goal is to get the button "start" to show a random number guess. This initial random number has to be used when the buttons "higher" or "lower" are being pressed. But if I do it in the way below, it gives me the error that x is not initialized. I know this is because I assigned a value to x in another if-loop but I don't know how to fix it. Can anyone help me?

  @Override
  public void onClick(View v) {
    int x;
    int lowBound;
    int highBound;
    if (v==start) {
        x=(int) Math.random()*1000;
        myTextView2.append("Random guess is "+String.valueOf(x));
    }
    if (v==higher) {
        lowBound=x;
        x= (int) (lowBound+Math.random()*(1000-lowBound));
        myTextView2.append(" New guess is "+String.valueOf(x));
    }
    if (v==lower) {
        highBound=x; 
        x=(int) (highBound-Math.random()*(1000-highBound));
        myTextView2.append(" New guess is "+ String.valueOf(x));
    }

}

Aucun commentaire:

Enregistrer un commentaire