-1
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

    int q = scanner.nextInt();
   scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

What is the use of this skip() method?

Can I replace it with another method to get the same result?

Falak Dhruve
  • 326
  • 1
  • 10
  • 1
    Your current code will not compile as it doesn't contain scanner declaration. But skipping line separator is one of solutions to problem described at [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045) – Pshemo Sep 24 '18 at 15:31
  • *"What is the use of this above .skip() method?"* Read the javadoc: [`skip(String pattern)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#skip-java.lang.String-). --- *"Would i replace with another method to get the same result?"* Don't know why you're asking for different method doing same thing, so difficult to answer, but javadoc shows example: `skip(Pattern.compile("\\R?"))`. – Andreas Sep 24 '18 at 15:42
  • If you want to skip whitespace, stopping after any newline, then try this answer: https://stackoverflow.com/a/42471816/7098259 – Patrick Parker Sep 24 '18 at 15:49

1 Answers1

0

Let's read the docs for skip:

Skips input that matches a pattern constructed from the specified string.

So skip tells the scanner to not read some parts of the user input, and continue after those parts. Here, your pattern matches a Windows new line character \r\n, or one of these...

  • U+2028 LINE SEPARATOR
  • U+2029 PARAGRAPH SEPARATOR
  • U+0085 NEXT LINE (NEL)

...if such a pattern exists.

Why does the programmer write this? A possible explanation is to avoid the next call to nextLine returning an empty string. See this question for why this happens.

Would i replace with another method to get the same result?

You could call skip(Pattern.compile("...")), but really it's just another overload of the same method. The closest to what you are doing is probably nextLine, which uses a similar pattern to yours.

Sweeper
  • 145,870
  • 17
  • 129
  • 225