Scanner 类中的 next() 和 nextLine() 方法有什么区别? [英] What's the difference between next() and nextLine() methods from Scanner class?

查看:29
本文介绍了Scanner 类中的 next() 和 nextLine() 方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

next()nextLine() 的主要区别是什么?
我的主要目标是使用 Scanner 读取所有文本,它可以连接"任何来源(例如文件).

What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be "connected" to any source (file for example).

我应该选择哪一个?为什么?

Which one should I choose and why?

推荐答案

我总是喜欢使用 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

这篇关于Scanner 类中的 next() 和 nextLine() 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆