Scanner, useDelimiter

前端 未结 3 1434
误落风尘
误落风尘 2020-12-12 02:11

I encounter some problem when using useDelimiter from the Scanner class.

Scanner sc = new Scanner(System.in).useDelimiter(\"-\");
while(sc.hasNext())
{
    S         


        
相关标签:
3条回答
  • 2020-12-12 02:48

    How I would do it follows:

    Scanner stdin = new Scanner(System.in);
    String s = stdin.nextLine();
    String[] splitInput = s.split("-", -1);
    

    You will now have an array of Strings that contain the data between all of the -s.

    0 讨论(0)
  • 2020-12-12 02:52

    You could use an alternative delimiter string useDelimiter( "-|\n" ); It works with a String argument as well as by reading from System.in. In case of System.in this requires you to press enter at the end of the line.

    0 讨论(0)
  • 2020-12-12 03:11

    If the Scanner didn't wait for you to enter another - then it would erroneously assume that you were done typing input.

    What I mean is, the Scanner must wait for you to enter a - because it has no way to know the length of the next input.

    So, if a user wanted to type A-B-CDE and you stopped to take a sip of coffee at C, it woud not get the correct input. (You expect [ A, B, CDE ] but it would get [ A, B, C ])

    When you pass it in a full String, Scanner knows where the end of the input is, and doesn't need to wait for another delimiter.

    How I would do it follows:

    Scanner stdin = new Scanner(System.in);
    String input = stdin.nextLine();
    String[] splitInput = input.split("-", -1);
    

    You will now have an array of Strings that contain the data between all of the -s.

    Here is a link to the String.split() documentation for your reading pleasure.

    0 讨论(0)
提交回复
热议问题