3

Why does this print the entire string "1fish2fish"...

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    String input = "1,fish,2,fish";
    Scanner sc = new Scanner(input);
    sc.useDelimiter(",");
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
  }
}

But this only prints "1fish2" even though I enter "1,fish,2,fish"?

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    System.out.println("Enter your string: ");
    Scanner sc = new Scanner(System.in);
    sc.useDelimiter(",");
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
  }
}
Travis Smith
  • 622
  • 5
  • 22

3 Answers3

4

In the first case, the scanner doesn't need the last delimiter, as it knows that there are no more characters. So, it knows that the last token is 'fish' and there are no more characters to process.

In the case of a System.in scan, the fourth token is considered as completed only when the fourth ',' is entered in the system input.

Note that white spaces are considered as delimiters by default. But, once you specify an alternate delimiter using useDelimiter, then white space characters don't demarcate tokens any more.

In fact, your first trial can be modified to prove that white space characters are not delimiters any more...

  public static void main(String[] args) {
    String input = "1,fish,2,fish\n\n\n";
    Scanner sc = new Scanner(input);
    sc.useDelimiter(",");
    System.out.print(sc.nextInt());
    System.out.println(sc.next());
    System.out.print(sc.nextInt());
    System.out.println(sc.next());

    System.out.println("Done");
    sc.close();

  }

The new line characters will be treated as part of the fourth token.

Teddy
  • 4,009
  • 2
  • 33
  • 55
1

I checked the first snippet; it is correctly printing -

  1fish
  2fish

Link - http://code.geeksforgeeks.org/jK1Mlu

Please let us know if your expectation is different.

vv88
  • 163
  • 3
  • 14
0

Scanner waits for you to enter another ',' so when you will enter ',' then after that it will immediately prints fish after 1fish2.

so Pass 1,fish,2,fish, instead of 1,fish,2,fish

PVR
  • 885
  • 9
  • 18