nextLine()的坑

nextLine和next都是读取输入台输入的字符。

next()只读取有效字符,不会读取有效字符前的空格、tab、回车,读取到有效字符后遇到空格、tab、回车才会停止读取。
nextLine()会读取字符前后的空格、tab,不管是在字符前还是后遇到回车都会停止读取,读取的是回车前的所有字符。

next()平时用的比较多,一般没什么问题,主要是nextLine(),以及nextLine()在next()后面使用时会出现错误。

1.nextLine()

 		Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        System.out.println("s1:[" + s1 + "]");
        System.out.println(s1.length());

只输入回车,此时nextLine读取回车前面字符,此时没有字符,所以s1长度为0。
在这里插入图片描述
2.next()和nextLine()

		Scanner sc = new Scanner(System.in);
        String s1 = sc.next();
        String s2 = sc.nextLine();
        String s3 = sc.nextLine();
        System.out.println("s1:[" + s1 + "]");
        System.out.println("s2:[" + s2 + "]");
        System.out.println("s3:[" + s3 + "]");

当nextLine()在next()后面使用时,next()读取有效字符遇到后面的回车键停止读取,而这个回车键会被接下来的nextLine()读取,所以s2此时没有读取到内容。
所以如果nextLine()在next()后面使用时,要多加一个nextLine()来读取next()留下来的回车键。
在这里插入图片描述
3. nextLine()和nextLine()

		Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        System.out.println("s1:[" + s1 + "]");
        System.out.println("s2:[" + s2 + "]");

当两个nextLine()一起使用时,就不会出现2中的情况,所以可以用两个nextLine代替nextLine()+next()。
在这里插入图片描述

  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值