我正在尝试运行 randomText() 方法,该方法在方法内部有一个循环,每次等待 2 秒,然后再次循环运行。每次它应该生成一个随机数 1 或 0。如果它的 0 显示 LEFT,如果它生成 1 则显示 RIGHT。但实际上总是显示 LEFT 并没有改变!我不知道是线程问题还是原始代码。
public class MainActivity extends Activity {
Scanner in = new Scanner(System.in);
Button left , right ;
TextView text ;
int value , mistake , pressed ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//value = 0; // 0:left 1:right 2:didnt pressed any
mistake = 0; // max mistake = 3
left = (Button) findViewById(R.id.button1); // value of the key is 0
right = (Button) findViewById(R.id.button2); // value of the key is 1
text = (TextView) findViewById(R.id.textView1);
randomText();
//*** set actions
left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pressed = 1;
if(value != 0) { mistake++; }
}
});
right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pressed = 1;
if(value != 1) { mistake++; }
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void randomText(){
Random r = new Random();
for (int i=0;i<10 && mistake <=2 ;i++){
value = r.nextInt(2);
pressed = 0; //
if (value == 1)
text.setText("RIGHT");
else
text.setText("LEFT");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// We've been interrupted
}
if (pressed == 0) mistake++;
}
}
}