0

I am new to java and i am trying to create a simple program which would parse a string using delimiter. However whenever i try do this instead of printing the lines like this:

Hello World 
I am Bob 
how are you 

it prints out each character individually on its own line. Here is my code:

import java.util.Scanner;

public class ScannerDemo {

    public static void main(String args[]){ 
        String s = "Hello World|I am bob|how are you ";
        Scanner scan = new Scanner(s);
        scan.useDelimiter("|");
        System.out.println(scan.next());
        while (scan.hasNext()){
            System.out.println(scan.next());
        }

    }
}

Any help would be apreciated

  • 2
    `|` (pipeline) has a special meaning in regular expressions - you need to escape it. Read this very close topic: http://stackoverflow.com/questions/9808689/why-does-string-split-need-pipe-delimiter-to-be-escaped – PM 77-1 Jul 12 '16 at 21:19

2 Answers2

2

Please use different delimiter as PIPE has special character which needs to escaped.

If strictly need PIPE symbol then try

scan.useDelimiter("\\|");
Hari M
  • 415
  • 1
  • 6
  • 13
  • Just to add... I really dont know the purpose of your requirement. But if you just want to delimit only from String (not any other IO operation) then i would suggest you to use the split method in String class which will return String array. – Hari M Jul 12 '16 at 21:30
1

As Pm 77-1 has stated you have to escape the pipe character:

import java.util.Scanner;

    public class ScannerDemo {

    public static void main(String args[]){
        String s = "Hello World|I am bob|how are you ";
        Scanner scan = new Scanner(s);
        scan.useDelimiter("\\|");
        System.out.println(scan.next());
        while (scan.hasNext()){
            System.out.println(scan.next());
        }

    }
}
Abaddon666
  • 1,533
  • 15
  • 31