2013-11-24 1 views
2

내 CS 프로젝트에서 나는 객관식 퀴즈를하고 있습니다. 각 퀴즈에는 질문과 네 가지 가능한 답이 있습니다. 올바른 대답은 String으로 저장됩니다. 모든 잘못된 대답은 문자열 배열에 저장됩니다. 나는 그것들 각각을위한 버튼을 만들고 싶다. 하지만 올바른 답을 항상 같은 위치에두기를 원하지 않아 무작위로 배치하려고합니다. 무작위로 배치 한 후에는 문자열 배열에 대한 단추를 만드는 방법을 알지 못합니다. 도움!Java에서 배열의 각 요소를 버튼으로 만드는 방법은 무엇입니까?

` 공공 디스플레이() {

answer1 = new JButton("1"); 
    answer2 = new JButton("2"); 
    answer3 = new JButton("3"); 
    answer4 = new JButton(""); 
    question = new JLabel ("question?"); 
} 

public Display(String question1, String [] answers, String correct, String pictureName){ 
    //create a panel to hold buttons 

    SimplePicture background = new SimplePicture(pictureName); 
    JLabel picture = background.getJLabel(); 

    question = new JLabel(question1); 

    //assign answers to buttons 

    //generate a random number to determine where correct goes 
    int index = (int)(Math.random()*4); 

    //place correct answer in a certain button 
    if (index == 0){ 
     answer1 = new JButton(correct); 
    } 
    else if (index == 1){ 
     answer2 = new JButton(correct); 
    } 
    else if (index == 2){ 
     answer3 = new JButton(correct); 
    } 
    else if (index == 3){ 
     answer4 = new JButton(correct); 
    } 

    //fill other spots with answers 
    for (int i=0; i < answers.length; i++){ 
     this is where I need help 

     } 
    }` 
+0

어쩌면 시각적으로 도움이 될 것입니다. 원하는 결과를 이해하지 못합니다. –

답변

0

귀하의 질문에 대한 답변과

이제 편집 :

당신이 간단하게 사용할 수 있습니다 사전에 얼마나 많은 버튼 알고 있기 때문에 배열.

JButton[] buttons; 

buttons = new JButton[4] // or new JButton[answers.length] if you ever 
         // want to increase the amount of answers. 

//assign answers to buttons 

//generate a random number to determine where correct goes 
int index = (int)(Math.random() * 4); 

//put the correct answer to the random button: 
buttons[index] = new JButton(correct) 

//fill other spots with answers 
for (int i = 1; i <= answers.length; i++) { 
    buttons[(index + i) % answers.length] = new JButton(answers[i - 1]); 
} 

그래서이 경우에는 무엇을 당신은 % 자바에서 나머지 연산자입니다 잘 모릅니다. 따라서 (index + i)이 3을 초과하면 (answers.length은 3) 다시 0이되므로 IndexOutOfBoundsException이 표시되지 않습니다.

희망이 도움이됩니다.

+0

List와 함께 오류 메시지가 나타납니다. List는 generic이 아니며 인수가 인 경우 매개 변수화 할 수 없습니다. 어떻게해야합니까? – darknessofshadows

+0

흠 올바른 수입이 있는지 확인하십시오 : 위의 대답에 추가하십시오 – Octoshape

+0

@darknessofshadows 그게 효과가 있었나요? – Octoshape

관련 문제