且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scanner 类中的 next() 和 nextLine() 方法有什么区别?

更新时间:2023-01-11 21:01:37

我总是喜欢使用 nextLine() 读取输入,然后解析字符串.

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

使用 next() 只会返回分隔符之前的内容(默认为空格).nextLine() 返回当前行后自动向下移动扫描仪.

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

解析来自 nextLine() 的数据的有用工具是 str.split("\\s+").

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

有关 Scanner 类或 String 类的更多信息,请参阅以下链接.

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

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

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