2 回答

TA貢獻2021條經驗 獲得超8個贊
您應該打印到較小的索引,然后 ^rint 2 的較大列表,我使用printf它,因為它允許獲得對齊:
public void printAll() {
int minSize = Math.min(originalR6.size(), userInputR6.size());
for (int i = 0; i < minSize; i++) {
System.out.printf("%d. %-10s %d. %-10s%n", (i + 1), originalR6.get(i), (i + 1), userInputR6.get(i));
}
if (originalR6.size() < userInputR6.size()) {
for (int i = minSize; i < userInputR6.size(); i++) {
System.out.printf("%d. %-10s %d. %-10s%n", (i + 1), "/", (i + 1), userInputR6.get(i));
}
} else if (originalR6.size() > userInputR6.size()) {
for (int i = minSize; i < originalR6.size(); i++) {
System.out.printf("%d. %-10s %d. %-10s%n", (i + 1), originalR6.get(i), (i + 1), "/");
}
}
}
要得到
案子if
1. nomad 1. nomad
2. maverick 2. maverick
3. lion 3. /
案子 else if
1. nomad 1. nomad
2. maverick 2. maverick
3. lion 3. lion
4. / 4. lion
5. / 5. lion

TA貢獻1829條經驗 獲得超7個贊
索引兩個“數組”數據時,如果您嘗試索引數組/列表中的最后一個元素,您將得到index out of range,因為在最后一個元素之后只有深淵。
for (int i = 0; i <originalR6.size() && i <userInputR6.size(); i++) {
System.out.println((i+1) + ". " + originalR6.get(i) + "\t" + (i+1) + ". " + userInputR6.get(i));
}
i <userInputR6.size()作為附加條件添加到您的 for 循環條件中將停止您的index out of range錯誤,打印出的元素將簡單地忽略較長數組/列表的其余部分。
添加回答
舉報