Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Java print last word here?

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());
  }
}
like image 919
Travis Smith Avatar asked Mar 24 '26 00:03

Travis Smith


2 Answers

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.

like image 72
Teddy Avatar answered Mar 25 '26 14:03

Teddy


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.

like image 38
vv88 Avatar answered Mar 25 '26 14:03

vv88



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!