即使使用可运行和处理程序,我也无法在循环运行按钮单击时做到这一点。谁能告诉我哪里出错了?
{//Class start
Button roll;
int numberOfDice;
int diceCounter;
EditText diceBox;
EditText outputBox;
String diceNum;
Handler myHandler = new Handler();
private boolean Running;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_roller_screen);
roll = (Button) findViewById(R.id.roll_Button);
diceBox = (EditText) findViewById(R.id.numberOfDiceBox);
outputBox = (EditText) findViewById(R.id.outputBox);
roll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
myHandler.post(runner);
}
});
}
Runnable runner = new Runnable() {
int dicecounter = 1;
Random rand = new Random();
public void run() {
do{
int dice_Value = rand.nextInt((6 - 1) + 1) - 1;
diceNum = diceBox.getText().toString();
numberOfDice = Integer.parseInt(diceNum);
outputBox.setText("Dice"+dicecounter+dice_Value);
dicecounter++;
}while(diceCounter <= numberOfDice);
myHandler.post(this);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.roller_screen, menu);
return true;
}
}
我不知道这是我的逻辑,或者如果我使用的运行程序和处理程序完全错误。
这几乎肯定是一个无限循环的问题:dicecounter
从1开始,所以如果你在diceBox
中输入的值小于2,do..while
循环将永远不会终止。计数器应该从0开始,您应该验证用户输入的骰子值的数量(包括检查数字格式异常,除非编辑控件只允许数字?)
但是在任何情况下,为什么那里有一个do..while
循环呢?它所做的只是覆盖outputBox
中的文本,所以即使循环是固定的,所有用户将看到的都是最后一次循环迭代的结果。