我正在制作一个类似于徽标测验的测验游戏,我试图创建他们的应用程序所具有的输入样式。他们有随机混合的字母,用户必须找到构成正确答案的字母。到目前为止,我有一个数组列表,其中包含按钮和正确的答案字母,然后我遍历数组列表并将按钮文本分配给正确答案数组列表中的字母,但导致强制停止而没有错误。谁知道为什么?
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));
}
}
}
答案 0 :(得分:1)
我无法理解为什么app force会从你给出的代码中停止(看起来很好),但我发现了另一个问题:
//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
如果您不希望多次出现字符,可以在将它们设置为按钮文本后将其从allowed
中删除。
答案 1 :(得分:0)
你可以做到以下几点:
Button btn;
for(int i = 0; i < answer.size(); i++){
btn = buttons.get(Math.random() * (buttons.size()+1))
if(btn.getText == null){
btn.setText(String.valueOf(answer.get(i)));
}
}
然后用随机字母填写剩余字母:
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
// char[] alphabet = [a-z] May also work ;)
for(Button b: buttons){
if(b.getText == null){
b.setText(String.valueOf(answer.get(Math.random() * (alphabet.size()+1)));
}
}
假设这样做,这应该在一个随机按钮中放一个“回答”字母,然后用a-z中的其他字母填充其他按钮。
P.S:假设按钮文本默认为“null”,您可以/应该更改
答案 2 :(得分:0)
String[] Herifler={"q","ü","e","r","t","y","u","i","o","p","ö","ğ","a","s","d","F","G","H","J","K","L","ı","ə","Z","X","C","V","B","N","M","ç","ş"};
for(in i=0;i<30;i++) {
buttons.get(i).setText(Herifler[i]);
}
Collections.shuffle(buttons);