java - 随机文本应用程序连续显示相同文本 2 次或更多次
问题描述
我做了一个简单的应用程序,当你点击一个按钮时,它会显示一个随机文本。一切正常,但有时它会连续显示 2 或 3 次相同的文本。我知道我可以用 if 语句解决这个问题,但我不知道该怎么做。这是我的代码。
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
private static final String[] FACTS = {
"McDonald’s once made bubblegum-flavored broccoli",
"Some fungi create zombies, then control their minds",
"The first oranges weren’t orange",
"There’s only one letter that doesn’t appear in any U.S. state name",
"A cow-bison hybrid is called a “beefalo”",
"Johnny Appleseed’s fruits weren’t for eating",
"Scotland has 421 words for “snow”",
"The “Windy City” name has nothing to do with Chicago weather",
"Peanuts aren’t technically nuts",
"Samsung tests phone durability with a butt-shaped robot"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random = new Random();
int index = random.nextInt(FACTS.length - 0);
textView.setText(FACTS[index]);
}
});
}
}
解决方案
int index = random.nextInt(FACTS.length - 0);
while(FACTS[index].equals(textView.getText().toString()) {
index = random.nextInt(FACTS.length - 0);
}
textView.setText(FACTS[index]);
推荐阅读
- javascript - 引导模态的位置不正确
- neural-network - 如何创建 ONNX 文件?
- ios - ionic 3 支持的最低 iOS 版本是多少?
- elasticsearch - 如何将kibana中的查询输出表示为图形?
- xpath - 如何针对从正则表达式提取器提取的值运行每个循环
- kerberos - Ambari 在安装 Kerberos 时无法创建主体
- php - 从服务器获取数据时如何保持选中动态单选按钮
- apache-camel - apache camel - seda 端点多播
- filter - 根据日期删除重复响应
- azure - Azure 服务总线消息订阅在容器重启后停止工作