Scanner nextLine() 将空值分配给 String

Scanner nextLine() assigns empty value to a String

For some reason query = sc.nextLine(); code returns query "" for the Delete part. So that the second code block does not execute and outputs a wrong list (First index of the list is not removed because of the Delete 0). Any ideas why the second query not get assigned from sc.nextLine()?

public static void main(String[] args) {
    final int QUERY_LIMIT = 2;

    Scanner sc = new Scanner(System.in);

    String query = "";
    String insert = "Insert";
    String delete = "Delete";

    int initial = sc.nextInt();

    List<Integer> list = new ArrayList<>();
    List <Integer> insertList = new ArrayList<>();

    for (int i = 0; i< initial; i++){
        list.add(i, sc.nextInt());
    }

    int numberOfQueries = sc.nextInt();

    while (numberOfQueries > 0) {
        query = sc.nextLine();

    if (insert.equals(query)) {
        for (int y = 0; y < QUERY_LIMIT; y++) {
         insertList.add(y, sc.nextInt());
         }

         int insertIndex = insertList.get(0);
         int insertValue = insertList.get(1);

         list.add(insertIndex,insertValue);

        } else if (delete.equals(query)) {
            int deleteIndex = sc.nextInt();
            list.remove(deleteIndex);
        }

        numberOfQueries--;
    }
    sc.close();
    list.forEach(a -> System.out.print(a +" "));
}

样本输入

5
12 0 1 78 12
2
Insert
5 23
Delete
0

预期输出

0 1 78 12 23

我的代码输出

12 0 1 78 12 23 

nextLine() returns 当前位置和下一行结尾之间的文本。

nextInt()在刚刚读取的整数后离开当前位置;这可能就在一行结束之前。

因此,在该点 returns 调用 nextLine() 行尾和该行尾之间的所有内容。也就是说,一个空字符串。

要可靠地使用扫描仪,您必须始终了解当前位置。

在使用 sc.nextInt()

阅读 5 23 后没有前进到换行符

文档 https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()nextLine()

Advances this scanner past the current line and returns the input that was skipped.