在我的java代码中,我随机选择一个数字并从数组中获取数字所赋值的值/字符串。这工作正常,但它已被提取后,我想要将数字存储在列表或数组中,然后当再次生成数字时,我可以检查该数字是否存在于数组或列表中,以及它是否会选择另一个数字,如果不匹配,则显示array.xml中该数字的值/字符串。这怎么能实现?我的代码是否正确实现?检查你的列表/数组中是否存在随机数
array.xml
<array name="OneTimesTables">
<item>1 x 1 = </item>
<item>1 x 2 = </item>
<item>1 x 3 = </item>
<item>1 x 4 = </item>
<item>1 x 5 = </item>
<item>1 x 6 = </item>
<item>1 x 7 = </item>
<item>1 x 8 = </item>
<item>1 x 9 = </item>
<item>1 x 10 = </item>
<item>1 x 11 = </item>
<item>1 x 12 = </item>
</array>
我的Java代码
public class Test extends AppCompatActivity {
String[] MyArray;
TextView Questions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
final List<String> PastQuestions = new ArrayList<String>();
MyArray = getResources().getStringArray(R.array.OneTimesTables);
Questions = (TextView)findViewById(R.id.RandomTestActivity_textView);
Button button = (Button)findViewById(R.id.RandomTestActivity_button);
int count = (new Random()).nextInt(12);
Questions.setText(MyArray[count]);
PastQuestions.add(MyArray[count]);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int count = (new Random()).nextInt(12);
if (MyArray[count].equals(PastQuestions)) {
int count2 = (new Random()).nextInt(12);
Questions.setText(MyArray[count2]);
PastQuestions.add(MyArray[count2]);
} else {
Questions.setText(MyArray[count]);
PastQuestions.add(MyArray[count]);
}
}
});
RandomiseArray();
}
private void RandomiseArray() {
ArrayList<String> list = new ArrayList<>();
for(String item: MyArray){
list.add(item);
}
Collections.shuffle(list);
}
}
了代码正确实现这一点? – Ceelos
不,因为它会一遍又一遍地打印相同的数字! – RexDough