我的程序應該重複一個方法,直到按下按鈕。 我想這一點,但不工作:Android編程:我如何擺脫while循環?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
public void onClick (View v){
switch(v.getId()) {
case R.id.button1:
mainprogram();
break;
case R.id.button2:
perform = false;
break;
}
}
public void mainprogram(){
while(perform == true){
speak();
}
}
(當然我編寫的「說話()」方法)
你能告訴我哪裏出了問題或者有任何方法解決它?
:
你可以閱讀更多有關揮發性這裏。你可能想把方法代碼放到循環中,然後使用break;'在循環外部 – SMR
使'perform'成爲'transient'。由於優化編譯器,while循環總是爲true。當你進入transient循環時,'perform'值會在進入while循環之前被檢查。 – Rahul