我想从答案数组中的每个第四个元素循环,我的代码无效。
这是我需要的输出:
Question 1
Answer 1
Answer 2
Answer 3
Answer 4
Question2
Answer A
Answer B
Answer C
Answer D
这是我得到的输出:
Question 1
Answer 1
Answer 2
Answer 3
Answer 4
Question 2
Answer 1
Answer 2
Answer 3
Answer 4
这是我写的代码:
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]);
}
}
答案 0 :(得分:1)
你可能只是稍微改变你的代码逻辑
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]);
答案 1 :(得分:0)
用这个
替换第二个循环定义for (int j = i*4; j<(i*4+4); j++) {
另外,用这个
替换第三行question[1] = "Question 2";
我认为这是您发布的示例代码中的拼写错误。