首页 > 编程语言 > 详细

Java中的Scanner类

时间:2020-04-27 19:51:34      阅读:62      评论:0      收藏:0      [点我收藏+]

nextInt(): it only reads the int value, nextInt() places the cursor(光标) in the same line after reading the input.

  (nextInt()只读取数值,剩下"\n"还没有读取,并将Scanner类读取依靠的cursor放在数值后面,"\n"前面,因此如果用nextInt()读取后,再用nextLine()读取,读取到的是换行符)


next(): read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.

  (next()只读空格之前的数据,并且cursor指向本行)next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。
nextLine(): 则可以扫描到一行内容并作为一个字符串而被获取到。如果要读取带空格的一串字符串还是需要使用nextLine(),而非next()方法。

循环时使用hasNext():

  遇到hasNext()时,Scanner也会阻塞,等待你输入,等你输入后返回true。当Scanner缓存区中有值可读时,会返回true,若没有,会一直阻塞等待你输入。

  当我们想退出用hasNext作条件的while()循环时,那么要么控制台手工输入ctrl+z,要么 while(!sc.hasNext("#"))约定当一行输入#时退出。

  实际线上笔试题中,要采用hasNext循环应对多组数据测试数据。

Java中的Scanner类

原文:https://www.cnblogs.com/jicongcong/p/12789475.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!