发布于 2年前

Java Scanner类next和nextLine的区别

JavaDoc解析

  • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
  • next(): Finds and returns the next complete token from this scanner.
  • nextLine(): Advances this scanner past the current line and returns the input that was skipped.

next():next方法是根据空白字符分割,遇到空白字符即返回

nextLine():nextLine方法是根据换行符分割,并且会包括除换行符外的空白字符。

示例

Scanner sc = new Scanner(System.in);
//加入输入的是:aaa bbb ccc
String s1=sc.next();
//s1="aaa"
String s2=sc.nextline();
//s2=" bbb ccc"
©2020 edoou.com   京ICP备16001874号-3