1

Recently I started learning Java. Probably this is a stupid question: using 'p' character as delimiter for my Scanner I expect the output will be

42

17

Hello World

while it is

42

17

pHello World

Delimiter may be excluded from the tokens of the Scanner, so why also 'p' char is printed in the last line?

'''

public static void main(String[] args) {
    String s = "42p17pHello World";
    Scanner scan = new Scanner(s);
    scan.useDelimiter("p");
    System.out.println(scan.nextInt());
    System.out.println(scan.nextInt());
    System.out.println(scan.nextLine());
    scan.close();
}

'''

1 Answers1

1

Calling nextLine() reads the next line from the scanner and does not seem to stop at the delimiter. Replace the nextLine() call with next().

Nomad
  • 118
  • 1
  • 4