What's the difference between next() and nextLine() methods from Scanner class?

后端 未结 14 2004
你的背包
你的背包 2020-11-21 05:32

What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be \"con

14条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 06:34

    I always prefer to read input using nextLine() and then parse the string.

    Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.

    A useful tool for parsing data from nextLine() would be str.split("\\s+").

    String data = scanner.nextLine();
    String[] pieces = data.split("\\s+");
    // Parse the pieces
    

    For more information regarding the Scanner class or String class refer to the following links.

    Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

    String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

提交回复
热议问题