Stoodent
Stoodent

Reputation: 29

How to use Scanner to extract integers from {int:int}?

I have to read integers from stdin, it comes in following format:

{4:11},{23:29},{1:7}...

I tried to use scanner delimiter, but I think it has problem with the first '{'

Scanner scanner =  new Scanner(System.in).useDelimiter("\\D");
while (scanner.hasNext()){
  int x = scanner.nextInt();
  int y = scanner.nextInt();
}

I get this exception:

Exception in thread "main" java.util.InputMismatchException
 at java.base/java.util.Scanner.throwFor(Scanner.java:939)
 at java.base/java.util.Scanner.next(Scanner.java:1594)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
 at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
 at Algorithm.main(Algorithm.java:63)

Upvotes: 2

Views: 128

Answers (2)

Akiner Alkan
Akiner Alkan

Reputation: 6872

You are specifying a delimiter pattern with the following

    scanner.userDelimiter("\\D"); // This \\D is pattern which will be matched.

You need to specify the pattern it like following:

    scanner.userDelimiter("\\D+") // With + keyword you are saying that it can be 1 or more.

Latest working code should look like following:

    Scanner scanner =  new Scanner(System.in).useDelimiter("\\D+");
    while(scanner.hasNext()){
        int x = scanner.nextInt();
        int y = scanner.nextInt();

        System.out.println("x: " + x);
        System.out.println("y: " + y);
    }

The other example is explicitly parsing the string with regex which you may not needed to if you only looking for delimiter pattern matching.

Note: Since you getting with nextInt(), and not validating the input so if there is invalid input(different input does not contain int) then you will get exception

Upvotes: 2

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

You simply need to extract continuous sequences of digits, regardless of the delimiter. You can read input line by line and parse with a \d+ regex:

Pattern pattern = Pattern.compile("\\d+");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  Matcher matcher = pattern.matcher(line);
  while (matcher.find()) {
    System.out.println(matcher.group());
  }
}

Upvotes: 1

Related Questions