#java #android
#java #Android
Вопрос:
Я создал простое приложение, которое показывает вам случайный текст при нажатии кнопки. Все это работает нормально, но иногда он показывает один и тот же текст 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]);
}
});
}
}
Комментарии:
1. Когда вы говорите «иногда», вы имеете в виду примерно 1 раз из 10?
Ответ №1:
int index = random.nextInt(FACTS.length - 0);
while(FACTS[index].equals(textView.getText().toString()) {
index = random.nextInt(FACTS.length - 0);
}
textView.setText(FACTS[index]);
Ответ №2:
Вы знаете, что это случайно , так что это нормально, чтобы сделать то же значение несколько раз подряд. Но если вы хотите предотвратить это, вы можете просто сохранить предыдущий индекс.
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
int lastIndex = 0;
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;
do {
index = random.nextInt(FACTS.length - 0);
} while (index == lastIndex);
lastIndex = index;
textView.setText(FACTS[index]);
}
});
}
}
Комментарии:
1. Можете ли вы объяснить мне, что вы думаете о сохранении предыдущего индекса. Мне действительно трудно это понять.
2. Что вы имеете в виду под «что вы думаете»? Я думаю, что это хороший способ предотвратить случайное повторение. Я даже использовал нечто подобное в своем проекте, чтобы выбрать около 10 случайных значений без единого повторения (таким образом, все 10 значений были случайными и были уникальными)
Ответ №3:
Вы можете просто сохранить свою последнюю строку, сгенерированную случайным образом, в переменной и проверить, совпадает ли новый текст:
String testString = "";
//now in your method that generates this random string you need to compare
//the generated string into your string variable.
//for example in your string generating method (in your case its the button click and generated string is FACTS[index]):
if(generatedString.equals(testString)){
//your strings are the same and you need to generate a new string
}else{
//your strings are not the same and you are good to go
}