我对Android有点陌生。开发一个应用程序,让用户输入一个数字,然后计算斐波那契数列,然后以 1 秒的间隔显示数列中的每个元素。但是当我尝试在 for 循环中使用线程进行显示时,我遇到了一个问题。我尝试从数组列表中打印,但我的计数器变量 (j) 出现错误。我尝试在一个更简单的应用程序中运行同样的方法,并且数组列表工作得很好。我不知道为什么这次它不起作用。我希望这是一个简单明显的错误。谁能告诉我为什么?代码贴在下面:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
Thread thread;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
//Attempt to clear TextView
textView.setText("");
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Clear Textview
String array = " ";
fibList.clear();
textView.setText(array);
final String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
Log.i("TEST", "ARRAY"+fibList);
thread = new Thread(new Runnable(){
@Override
public void run(){
for(int j = 0; j < fibList.size(); j++){
runOnUiThread(new Runnable(){
@Override
public void run(){
//ERROR OCCURS HERE: Cannot refer to a non-final variable j
//inside an inner class defined in a different method
textView.append(fibList.get(j).toString());
textView.append("");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //wait one second
}
}
});
thread.start();
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
@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;
}
}