gpt4 book ai didi

java - Android 将数组值分配给按钮

转载 作者:行者123 更新时间:2023-12-01 12:41:10 25 4
gpt4 key购买 nike

我正在制作一个类似于 Logo 测验的测验游戏,我正在尝试创建他们的应用程序所具有的输入样式。它们有随机混合的字母,用户必须找到组成正确答案的字母。到目前为止,我有一个包含按钮和正确答案字母的数组列表,然后我循环遍历数组列表并将按钮文本分配给正确答案数组列表中的字母,但会导致强制停止而不会出现错误。有谁知道为什么吗?

ArrayList<Character> answer = new ArrayList<Character>();
ArrayList<Button> buttons = new ArrayList<Button>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btn1 = (Button) findViewById(R.id.button1);
Button btn2 = (Button) findViewById(R.id.button2);
Button btn3 = (Button) findViewById(R.id.button3);
Button btn4 = (Button) findViewById(R.id.button4);
Button btn5 = (Button) findViewById(R.id.button5);
Button btn6 = (Button) findViewById(R.id.button6);
Button btn7 = (Button) findViewById(R.id.button7);
Button btn8 = (Button) findViewById(R.id.button8);
Button btn9 = (Button) findViewById(R.id.button9);
buttons.add(btn1);
buttons.add(btn2);
buttons.add(btn3);
buttons.add(btn4);
buttons.add(btn5);
buttons.add(btn6);
buttons.add(btn7);
buttons.add(btn8);
buttons.add(btn9);

String testAnswer = "Answer";
//convert to chars and add to arraylist for shuffling
for(char a : testAnswer.toCharArray()){
answer.add(a);
}
Collections.shuffle(answer);


//loop over buttons and letters and assign each button with a letter
for(char a : answer){
for(Button bb : buttons){
bb.setText(String.valueOf(a));
}
}

}

最佳答案

我不明白为什么应用程序强制从您给出的代码停止(看起来很好),但我发现了另一个问题:

//loop over buttons and letters and assign each button with a letter
for(char a : answer){
for(Button bb : buttons){
bb.setText(String.valueOf(a));
}
}

此代码不会为每个按钮分配不同的字母,而是为所有按钮分配相同的字母。
相反,这样做:

// omit unnecessary answer.shuffle() (`answer` will be shuffled anyway afterwards)

String allowed = "abcdefghijklmnopqrstuvwxy"; // add all allowed characters here

for (int i = 0; i < answer.size(); i++)
buttons.get(i).setText("" + answer.get(i));

Random r = new Random();
for (int j = answer.size(); i < buttons.size(); j++)
buttons.get(j).setText("" + allowed.charAt(r.nextInt(0, allowed.length())); // get a random character from `allowed`

Collection.shuffle(buttons); // shuffle buttons, so that they are in random order

如果您不希望字符多次出现,可以在将它们设置为按钮文本后将其从允许中删除。

关于java - Android 将数组值分配给按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084120/

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