0

I'm trying to make a GUI for a quiz program with several questions displayed at the same time with 3 answers each. The anwsers are displayed in radiobuttons. I have to test each radio button 3 times(if selected/good/bad anwser, none selected). Each radiobuttons name are like this:KxValaszy. Where x represents the number of the question, and the y represents the number of the answer. So the first questions first anwers's radiobutton name is:"K1Valasz1", and so on. My problem is that testing each radiobutton 3 times is quite a lot of typing, is there any way to dinamically create the names of these radiobuttons? Like something like this?

for (int i = 1; i <= 10; i++) {
    for (int k = 1; k <=3; k++) {
        answer = ("K" + i + "Valasz" + k);
        if (KvizValaszok.answer.getText().equlas("OneGooDAnswer");
        NumberOfGoodAnswers++;
    }
}

This is an altered portion of the code and obviosly not working is just wanted to furter demonstrate exactly what do I want to do. Sorry for my English, and my Java skills I just started coding in Java :)

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • You should always search before asking, such as [Java dynamic variable name](https://www.google.com/#q=site:stackoverflow.com+java+dynamic+variable+name) and you'd have your answer. But no, this is not allowed, and thankfully so. Use either a Map or an Array or an ArrayList. – Hovercraft Full Of Eels May 02 '17 at 16:14
  • Note yours is an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) where you ask how to make dynamic variable names when the solution is to use a different approach entirely. Your problem looks to be due to code redundancy, and solutions include creating a method, or creating classes to reduce code repetition. – Hovercraft Full Of Eels May 02 '17 at 16:17
  • Myself, if I were creating a quiz GUI program, I'd try to structure my program a la M-V-C or Model-View-Controller, the key being to separate the model (the program logic) from the view (the GUI), would make the view as "dumb" as possible, and leave all the testing for correctness in the model. So for instance, I'd create a non-GUI Question class with 2 incorrect answer Strings and 1 correct answer String, give this class a method that tests if a chosen String matches the answer String, give it a method to randomly shuffle the Strings,... and then create a JPanel that could display a Question. – Hovercraft Full Of Eels May 02 '17 at 16:20

0 Answers0