Java中Scanner的nextInt(),next(),nextLine()方法总结

一杯JAVA浓 做棵大树 7年前 (2017-11-12) 2264次浏览 0个评论
前言:借别人的例子做个总结。
原文出处:http://www.cnblogs.com/gold-worker/archive/2013/04/10/3013063.html

    代码一

 

package cn.dx;
 import java.util.Scanner;
 public class ScannerTest {

     public static void main(String[] args) {
         Scanner in =  new Scanner(System.in);
         System.out.println("请输入一个整数");
         while(in.hasNextInt()){
             int num = in.nextInt();
             System.out.println("请输入一个字符串");
             String str = in.nextLine();
             System.out.println("num="+num+",str="+str);
             System.out.println("请输入一个整数");
         }
     }
 }

  结果一


请输入一个整数
1231
请输入一个字符串
num=1231,str=
请输入一个整数

第二个 String 类型的参数没有读取进来。

自己查看了下nextInt()和 nextLine()方法的官方文档

 

 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. 

  nextInt()方法会读取下一个 int 型标志的 token.但是焦点不会移动到下一行,仍然处在这一行上。当使用 nextLine()方法时会读取改行剩余的所有的内容,包括换行符,然后把焦点移动到下一行的开头。所以这样就无法接收到下一行输入的 String 类型的变量。

    代码二

 

package cn.dx; 
 import java.util.Scanner;
 public class ScannerTest {

     public static void main(String[] args) {
         Scanner in =  new Scanner(System.in);
         System.out.println("请输入一个整数");
         while(in.hasNextInt()){
             int num = in.nextInt();
             System.out.println("请输入一个字符串");
             String str = in.next();
             System.out.println("num="+num+",str="+str);
             System.out.println("请输入一个整数");
         }
     }
 }

  结果二

请输入一个整数
123
请输入一个字符串
sdjakl
num=123,str=sdjakl

请输入一个整数
213 jdskals
请输入一个字符串
num=213,str=jdskals
请输入一个整数

   总结:


做棵大树 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Java 中 Scanner 的 nextInt(),next(),nextLine()方法总结
喜欢 (1)
[欢迎投币]
分享 (0)
关于作者:
一个整天无所事事的,有时候忽然热血的孩子
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
Ads Blocker Image Powered by Code Help Pro

靓仔,把广告拦截插件关了吧~ 给孩子两毛钱广告费吧~

我们检测到您使用了广告屏蔽插件,建议您把 广告屏蔽插件关闭 或者 添加本站为白名单 即可

个人网站运营不易,感谢体谅啊~

打赏博主会让我更加开心啦~(。・∀・)ノ

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock