我正在嘗試創建一個小程序,該按鈕在按下按鈕時會從的Media
對象中選擇一個隨機創意媒體。它不工作。我是Android的初學者,我不知道自己會出錯。任何人都可以在我的代碼中發現錯誤?從android的數組列表中選擇一個隨機項 - 爲什麼我的代碼不工作?
import java.util.ArrayList;
import java.util.Random;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button2;
TextView tvRandomMedia;
Random rnd = new Random();
ArrayList<Media> media = new ArrayList<Media>();
Media m1 = new Media("painting");
Media m2 = new Media("Paper sculpturing");
Media m3 = new Media("sawing");
Media m4 = new Media("writing");
Media m5 = new Media("dance");
Media m6 = new Media("playing music");
Media m7 = new Media("Graphic design");
Media m8 = new Media("photography");
button2=(Button) findViewById(R.id.button2);
button2.setOnClickListener((View.OnClickListener) button2Listener);
media.add(m1);
media.add(m2);
media.add(m3);
media.add(m4);
media.add(m5);
media.add(m6);
media.add(m7);
media.add(m8);
tvRandomMedia = (TextView) findViewById(R.id.textView1);
}
OnClickListener button2Listener=new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
doRandomMedia();
}
public void doRandomMedia() {
int creativity = rnd.nextInt(media.size());
Media expression = media.get(creativity);
System.out.print("The media of this week is "+ expression);
}
}
}
那麼發生了什麼? – CubeJockey
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –
發生了什麼*改爲*,或者你能描述一下比「不工作」更好嗎? – nitind