尝试打印ArrayList的前4个元素时出错

时间:2018-09-30 20:48:14

标签: java for-loop arraylist while-loop

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out-of-bounds for length 1
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Unknown Source)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Unknown Source)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Unknown Source)
        at java.base/java.util.Objects.checkIndex(Unknown Source)
        at java.base/java.util.ArrayList.get(Unknown Source)
        at HelloWorld.main(HelloWorld.java:27)

我的程序是一个待办事项,如下:

import java.util.Scanner; 
import java.util.ArrayList;

/**
 * @author Troy
 *
 */
public class HelloWorld {

    /** A very simple to-do list that asks for input and then prints out the list 
     * in the form of an ArrayList: eg:
     Here is today's to-do list:
     [Wake up, Walk the dog,Eat breakfast, Make the bed]
      */
    public static void main(String[] args) {
        // I chose an ArrayList because the size does not have to be predetermined.
        ArrayList<String> to_do = new<String>ArrayList();
        System.out.println("What would you like to add to your to-do list?");
        Scanner user_input = new Scanner(System.in);
        //While the user_input still has entries, perform the following:
        while (user_input.hasNextLine()) {
            //Add next entry in the to-do list(user_input) to the ArrayList
            to_do.add(user_input.nextLine());
            System.out.println("\n");
            /**Print out the ArrayList(to_do) 4 elements at a time. */
            for (int i = 0; i < 5; i++ ) {
                System.out.println("Your list for today is: " + "\n" + to_do.get(i));

            }

            }
    }
}

我在程序末尾编写to_do.get(i)时,立即收到上述错误消息。 另一个奖励问题是如何在不影响最终ArrayList的输出的情况下结束while循环?

1 个答案:

答案 0 :(得分:2)

您的for循环尝试从列表中访问尚不存在的值。这就是为什么您获得IndexOutOfBoundsException的原因。

如果将for循环中的测试表达式替换为检查列表大小的内容,而不是将其硬编码为5,它将起作用:

for (int i = 0; i < to_do.size(); i++)

您可以使用break结束输入周期。 在将输入添加到列表之前,请先检查输入内容,方法是先将其分配给本地变量。例如,如果它是空格(作为用户没有更多输入的信号),则从while循环执行中断。

String input = user_input.nextLine();
if (" ".equals(input) || i == 4) {
    break;
}
to_do.add(input);

如果您想一次仅打印4个条目,它将看起来像这样:

System.out.println("Your list for today is: " + "\n");
for (int page = 0; page <= (to_do.size() / 4); page++) {
    for (int offset = 0; offset + page * 4 < to_do.size() && offset < 4; offset++) {
            System.out.println(to_do.get(page * 4 + offset));
        }
        user_input.nextLine();
    }
}