Java 2D array is not saving the user input

Viewed 103

I am using a GUI and every time the user inputs the information, it won't save to the 2D array.

public String [][] arrayQues = new String[2][5];

textFieldAns = new JTextField();
textFieldAns.setBounds(127, 130, 272, 42);
textFieldAns.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String Ans = textFieldAns.getText();
        textFieldAns.selectAll();
        arrayQues[1][0] = Ans;
    }
});

I know it does not save to the 2D array because in another class that inherits the above class, the randQ label shows up as null

    Random r = new Random();
    int randAnswer = r.nextInt(arrayQues[1].length);
    int randQuestion = r.nextInt(arrayQues[0].length);
    String randQ = arrayQues[0][randQuestion];
    String randA = arrayQues[1][randQuestion];

    JLabel randomQuestion = new JLabel(randQ);
    randomQuestion.setBounds(112, 61, 269, frame.getContentPane().add(randomQuestion);

1 Answers

create a variable to know, at which index the next question/answer will be stored into arrayQues.

private int quesIndex;

the in you method actionPerformed, call

String answer = textFieldAns.getText();
textFieldAns.selectAll();
arrayQues[1][quesIndex] = answer;

your questions should be inserted accordingly before taking the answer

arrayQues[0][quesIndex] = "insert your question here";
Related