0

I want to loop from every fourth element in the answer array, and my code is not working.

This is the output I need:

Question 1
Answer 1
Answer 2
Answer 3
Answer 4
Question2
Answer A
Answer B
Answer C
Answer D

This is the output I am getting:

Question 1
Answer 1
Answer 2
Answer 3
Answer 4
Question 2
Answer 1
Answer 2
Answer 3
Answer 4

This is the code I wrote:

String[]question = new String[2];
question[0] = "Question 1"; 
question[2] = "Question 2";      

String[]answer = new String[8];
answer[0] = "Answer 1";
answer[1] = "Answer 2";
answer[2] = "Answer 3";
answer[3] = "Answer 4";
answer[4] = "Answer A";
answer[5] = "Answer B";
answer[6] = "Answer C";
answer[7] = "Answer D";

for (int i = 0; i < question.length; i++) {
    System.out.println(question[i]);
    for (int j = 0; j<4; j++) {
        System.out.println(answer[j]);
    }
}
1
  • System.out.println(answer[i*4 + j]). Also it should be question[1] = "Question 2"; (array index can't be equal to its size). Overall it is comfortable to define arrays as String questions[] = {"Question1", "Question2"}; Commented Jul 14, 2016 at 16:41

2 Answers 2

2

you may just change your code logic a little bit

 String[]question = new String[2];
question[0] = "Question 1"; 
question[2] = "Question 2";      

String[]answer = new String[8];
answer[0] = "Answer 1";
answer[1] = "Answer 2";
answer[2] = "Answer 3";
answer[3] = "Answer 4";
answer[4] = "Answer A";
answer[5] = "Answer B";
answer[6] = "Answer C";
answer[7] = "Answer D";

for (int i = 0; i < question.length; i++) {

    System.out.println(question[i]);

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


            System.out.println(answer[j]);
Sign up to request clarification or add additional context in comments.

Comments

0

Replace the second loop definition with this

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

Also, replace the third line with this

question[1] = "Question 2";

I think this is a typo in the sample code you posted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.