我有 2 个数组列表
ArrayList<Character> answer = new ArrayList<Character>();
ArrayList<Button> buttons = new ArrayList<Button>();
答案 1 包含字符串 correctA 中的一堆字符,按钮中保存了 20 个按钮。我想要做的是从答案数组中获取每个字母,并将每个字母分配给一个单独的按钮。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStuff();
//split string and add to array
String correctA = "TestAnswer";
for(char a : correctA.toCharArray()){
answer.add(a);
}
Collections.shuffle(answer);
Button btn;
//in this case will loop 10 times as there are 10 characters in "testAnswer"
for(int i = 0; i < answer.size(); i++){
Random myRandomizer = new Random();
btn = buttons.get(myRandomizer.nextInt(buttons.size()));
char a = answer.get(myRandomizer.nextInt(answer.size()));
btn.setText(String.valueOf(a));
}
}
我尝试了几种不同的随机方式,每次我运行该应用程序时,只有 7 或 8 个按钮填充了一个字母,而不是它应该的 10 个,我做错了什么?
最佳答案
您每次都选择一个随机的 Button
和一个随机的 char
,但是在整个循环过程中,Button
被选择了两次,留下另一个 Button
未被触及。
您已经打乱了 correctA
中的字母,所以它们已经随机化了。只需按顺序选择每个按钮和每个字符。
for(int i = 0; i < answer.size(); i++){
btn = buttons.get(i);
char a = answer.get(i);
btn.setText(String.valueOf(a));
}
关于java - Android/Java 循环无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25089234/