我需要从String []数组中获取每4个元素并迭代它们

时间:2015-07-02 12:21:57

标签: java arrays

我有一个包含字符串(答案)的数组,并获取每4个元素,并将它们分配给4个单选按钮。由于我是一个没有经验的程序员,我无法让它工作。

void set() // rework with array
{
    try {
        //sets the question label
        jb[4].setSelected(true);

        if (current < questions.length) {
            label.setText("Question " + (current + 1) + ": " + questions[current]);

            for (int j = current; j < (current * 4); j++) {

                // k goes through 0, 1 ,2 ,3 needed for the radio buttons
                for (int k = 0; k < 4; k++) { // was (i+3)
                    System.out.println("Cur= " + current + " * 4= " + (current * 4) + " J= " + j + " K= " + k);

                    //System.out.println(" J= " + j + " K= " + k);
                    jb[k].setText(answers[j] + " @ " + j);

                }
            }
        }

        for (int i = 0, j = 0; i <= 90; i += 30, j++) {
            jb[j].setBounds(50, 80 + i, 600, 20);
        }

    } catch (NullPointerException ex) {
        System.out.println("Error at: " + count + ex.getMessage()); //testing what's going on
    }
}

但是在第一次运行时(问题1)我没有得到任何设置到单选按钮的答案,而在其他所有问题上我得到了分配给所有这些的数组的第3,第7,第11等答案单选按钮。由于某种原因,无法使控制台输出适合代码块...

3 个答案:

答案 0 :(得分:0)

为什么不使用modulo:

if(x%4 == 0) {
    //your instructions
}

答案 1 :(得分:0)

我不建议对现有设计进行任何更改,因为您遵循的数据结构本身很复杂。

您可以通过以下简单的数据结构来满足您的应用要求:

有以下数据结构来存储问题及其相应的答案(假设有10个问题)。

// Represent map where key is question and value is list of 4 options.
Map<String, List<String>> questions = new HashMap<String, List<String>>(10);

具有数据结构以维护四个答案的列表,这些答案将作为上述数据结构中的值。

// Represent list of four answers.
List<String> answers = new java.util.ArrayList<String>(4);

迭代问题地图以获得预期结果。

for (Map.Entry<String, List<String>> entry : questions.entrySet()) {
    // Print question.
    System.out.println(entry.getKey());
    for (String answer : entry.getValue()) {
        // Print four options for question.
        System.out.println(answer);
    }
}

如果您发现这一点令人困惑,请随意提出疑问。

答案 2 :(得分:0)

找到解决方案。但它写得非常复杂,你应该把它变得更简单。

void set() // rework with array
{
try {
    //sets the question label
    jb[4].setSelected(true);

    if (current < questions.length) {
        label.setText("Question " + (current + 1) + ": " + questions[current]);

        int j = current*4;
        for (int k = 0; k < 4; k++) {

                jb[k].setText(answers[j+k]);

            }
        }
    }

    for (int i = 0, j = 0; i <= 90; i += 30, j++) {
        jb[j].setBounds(50, 80 + i, 600, 20);
    }

} catch (NullPointerException ex) {
    System.out.println("Error at: " + count + ex.getMessage()); //testing what's going on
}
}