Issues with Java Scanner

Viewed 60

I meet a problem while using Java Scanner. When I used two nextLine() in the code, and there would be two "\n" in the string entered by me via command line. I did't understand why this happen, please help.

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Scanner;

public class TestScanner {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in, StandardCharsets.UTF_8.name());
        int num = Integer.parseInt(input.nextLine().trim());
        for (int i = 0; i < num; i++) {
            System.out.print(Arrays.toString(input.nextLine().trim().split(" ")));
        }
    }
}

enter image description here

this is my input: enter image description here

1 Answers

This issue only occurs when you run your program in an IDE, and the problem is the way the IDE works. You might want to report it as a probable bug to your IDE vendor. (I can reproduce this issue in IntelliJ IDEA 2022.1.1.)

If you run this from the command line, it works fine.

UPDATE

This has been fixed in IntelliJ IDEA 2022.1.2. It appears to be this issue: https://youtrack.jetbrains.com/issue/IDEA-293951

Related