java中Scanner.next()和Scanner.nextLine的区别图文详解
.next() 和 .nextLine
next()的使用
next() 读取空格前的内容
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); System.out.println(s); }
nextLine()的使用
nextLine() 读取一整行
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); System.out.println(s); }
.next() 和 .nextLine 的区别 nextLine() 读取一整行 next() 读取空格前的内容
.hasNext() 和 .hasNextLine
.hasNext()的使用
hasNext() 配合 next() 使用 和while 循环使用
一直判断当前行的数据,直到当前行没有数据
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { System.out.println(scanner.next()); } }
.hasNextLine()的使用
hasNext() 配合 next() 使用 和while 循环使用 一直判断输入的数据,一次读取一行,直到停止输入数据
停止输入快捷键 Ctrl + D
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while(scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } }
Scanner中next()方法与nextlLine()方法的区别:
next方法不能得到带空格的字符串,而nextLine()方法返回的是Enter键之前的所有字符
这是因为next()方法读取到空白符前的数据时结束了,然后把回车“\r”留给了nextLine();所以上面nextLine()没有输出,不输出不代表没数据,是接到了空(回车“/r”)的数据。
总结
到此这篇关于java中Scanner.next()和Scanner.nextLine区别的文章就介绍到这了,更多相关java Scanner.next()和Scanner.nextLine区别内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
mybatis返回list<Integer>时resultType写Integer问题
这篇文章主要介绍了mybatis返回list<Integer>时resultType写Integer问题,具有很好的参考价值,希望对大家有所帮助,2023-12-12基于 IntelliJ IDEA 模拟 Servlet 网络请求示例
这篇文章主要介绍了基于 IntelliJ IDEA 模拟 Servlet 网络请求示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-04-04RestTemplat中关于getForobject方法的使用
这篇文章主要介绍了RestTemplat中关于getForobject方法的使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-07-07
最新评论