码迷,mamicode.com
首页 > 其他好文 > 详细

关于 Scanner 的 nextLine( ) 方法

时间:2017-05-23 20:27:18      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:height   bsp   ann   操作   scanner   int   lang   data-   实现类   

先看以下代码:
  1. Scanner read = new Scanner(System.in);
  2. int a = read.nextInt();
  3. String str = read.nextLine();
  4. System.out.println(a);
  5. System.out.println(str);
试着输入:12、回车
发现程序终止了,直接输出了12,不能输入 str 了:
技术分享
 

原因是 read() 不会跳过回车符,nextLine() 会读回车符,输完12后输入的那个回车符直接就被读到 str 中了,这时 str 是一个回车符并被输出,所以有个空行。
解决办法:在第三行之前调一次 nextLine(),读掉上一次的回车符。

可以利用这一特性,用 readLine() 读回车符,实现类似“按回车继续”等的操作。

关于 Scanner 的 nextLine( ) 方法

标签:height   bsp   ann   操作   scanner   int   lang   data-   实现类   

原文地址:http://www.cnblogs.com/chendifan/p/6895795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!