我正在尝试运行randomText()方法,在方法内部我有一个循环,每次等待2秒然后再循环运行。每次它应该产生一个随机数1或0.如果它的0表示LEFT,如果它表示1表示正确。但实际上总是显示LEFT并且不会改变!我不知道它是Thread问题还是原始代码。
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++;
}
}
}
答案 0 :(得分:0)
首先,您在主线程中调用randomText()。这意味着,因为你在循环内设置为0,除非你在另一个线程中更改它,否则它将保持为0。按钮点击也发生在主线程上,因此在执行randomText()时,它们无法将其更改为其他内容。
这意味着在randomText()方法停止调用text.setText()之前,您将获得三次迭代。
此外,您应该为Random r调用Random(long seed)构造函数。通常建议使用种子的当前时间,因此Random对象应该像这样初始化:
Random r = new Random(System.currentTimeMillis());