我对编程很陌生并且我已经创建了这个应用程序,当按下按钮时会说一个笑话唯一的问题是当它到达应用程序崩溃的最后一个文本时,因为没有更多文本可供查看。我确定有一种方法可以在到达最后一个文本时从头开始再次启动数组,我只是不知道该怎么做。任何帮助都将非常感激!
这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView line = (TextView) findViewById(R.id.line);
Button bl = (Button) findViewById(R.id.bl);
final String[] jokes = {
"joke 1", "joke 2" , "joke 3" , "joke 4"
};
bl.setOnClickListener(new View.OnClickListener() {
int rando = (int) (Math.random() * 4);
@Override
public void onClick(View v) {
rando++;
line.setText(jokes[rando]);
}
});
}
答案 0 :(得分:1)
由于每次单击按钮时都会得到一个随机数,所以在访问数组之前只需要递增计数器:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView line = (TextView) findViewById(R.id.line);
Button bl = (Button) findViewById(R.id.bl);
final String[] jokes = {
"joke 1", "joke 2" , "joke 3" , "joke 4"
};
bl.setOnClickListener(new View.OnClickListener() {
int rando = (int) (Math.random() * 4);
@Override
public void onClick(View v) {
line.setText(jokes[rando]);
}
});
}
另一种选择是获取一个随机数,将其存储在一个字段中,然后在每次单击该按钮时递增它:
int rando; // store in a field in your Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView line = (TextView) findViewById(R.id.line);
Button bl = (Button) findViewById(R.id.bl);
final String[] jokes = {
"joke 1", "joke 2" , "joke 3" , "joke 4"
};
final int jokeCount = jokes.length;
rando = (int) (Math.random() * 4); // initialize only in onCreate
bl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (++rando >= jokeCount) { // increment in onClick
rando = 0; // reset counter when needed
}
line.setText(jokes[rando]);
}
});
}