通过API来弄清java中nextLine()与next()的区别

一 nextLine()

Advances this scanner past the current line and returns the input that was skipped.This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
总结之:跳过scanner所在行,并将此行作为String类返回值返回,不包括结尾的行分隔符。
所以,若遇到换行符,nextLine()的此次调用会失效,直接结束方法。

二 next()

Finds and returns the next complete token from this scanner.A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext returned true.

  1. 注意黑体字:“一个完整的部分是前面和后面都被分割符分割的”,这句话便表述了一个很常见的读取规则:输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉

  2. 在读取时,完整部分后面的分隔符没有被读取,仍存在缓冲区,若分隔符是换行符,则下次用nextLine()读取下一行以前,会遇到该换行符,而根据nextLine()的规则,它会跳过此行,结束此次读取。但用next()读取则没事,因为此时对next()来说完整部分的前面和后面都是分隔符----’\n’。

  3. 空格,tab,enter都是分隔符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值