我對Android有點新。使用一個讓用戶輸入數字然後計算斐波納契數列的應用程序,然後以1秒的間隔顯示序列中的每個元素。但是當我嘗試在for循環中使用線程顯示時,我遇到了一個問題。我嘗試從數組列表中打印,但它給我一個錯誤,我的計數器變量(j)。我試着在一個更簡單的應用程序中運行這個相同的確切方法,數組列表工作得很好。我不知道爲什麼這次不行。我希望這是一個簡單明顯的錯誤。誰能告訴我爲什麼?代碼下面貼:希望線程中出現簡單錯誤Android
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;
}
}
它的工作原理。非常感謝你。 – David 2013-05-10 18:29:58
不客氣。請將答案標記爲已接受。 – Blackbelt 2013-05-10 18:31:16