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));
}
}
If
v
is equal to anything other thanstart
, the variable will assigned tolowerBound
orupperBound
uninitialized.Unless I'm reading it wrong, this actually shows a flaw in your logic:
Every time
onClick
is called,x
will either be reset ifv == start
, or will be used uninitiated.x
should declared outside of the method since you need it to "survive" betweenonClicks
.