首页 > 解决方案 > 随机文本应用程序连续显示相同文本 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]);             
        }
    });
  }
}

标签: javaandroid

解决方案


int index = random.nextInt(FACTS.length - 0);
while(FACTS[index].equals(textView.getText().toString()) {
    index = random.nextInt(FACTS.length - 0);
}
textView.setText(FACTS[index]);

推荐阅读