0

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 +" "));
}

Sample Input

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

Expected Output

0 1 78 12 23

My code output

12 0 1 78 12 23 
TheCoder
  • 128
  • 12

2 Answers2

3

nextLine() returns text between the current position and the next end of line.

nextInt() leaves the current position after the integer just read; this may be just before the end of a line.

Therefore, calling nextLine() at that point returns everything between the end of the line and the end of that line. Which is to say, an empty string.

To use Scanner reliably, you have to be aware at all times where the current position is.

iggy
  • 1,328
  • 4
  • 3
  • *returns everything between the end of the line and the end of that line.* - this sounds a bit confusing although the answer as a whole is correct. – Janez Kuhar Aug 06 '21 at 00:11
2

Did not advance past a newline character after reading 5 23 with sc.nextInt()

The documentation https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine() says nextLine()

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

clwhisk
  • 1,805
  • 1
  • 18
  • 17