gpt4 book ai didi

java - 随机文本应用程序连续 2 次或更多次显示相同的文本

转载 作者:太空狗 更新时间:2023-10-29 16:25:41 25 4
gpt4 key购买 nike

我制作了一个简单的应用程序,它会在您单击按钮时向您显示随机文本。一切正常,但有时它会连续 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]);

关于java - 随机文本应用程序连续 2 次或更多次显示相同的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com