java中输入next()和nextLine()的区别

1.next() :next()方法在读取内容时,会过滤掉有效字符前面的无效字符,对输入有效字符之前遇到的
空格键、Tab键或Enter键等结束符,next()方法会自动将其过滤掉;只有在读取到有效字符之后,next
()方法才将其后的空格键、Tab键或Enter键等视为结束符;所以next()方法不能得到带空格的字符串.

2. nextLine() :表示读取一行,nextLine()方法字面上有扫描一整行的意思,它的结束符只能是Enter
键,即nextLine()方法返回的是Enter键之前没有被读取的所有字符,它是可以得到带空格的字符串的。

3.我们可以通过代码来测试
code1:

public class TestNext {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String a = in.next();
        String b = in.nextLine();
        System.out.println("a : " + a);
        System.out.println("b : " + b);
    }
}
输入:
aa aa
输出:
a : aa
b :  aa

Process finished with exit code 0
复制代码

code2:我们换了一个nextLine() 和next()的顺序

public class TestNext {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String b = in.nextLine();
        String a = in.next();
        System.out.println("a : " + a);
        System.out.println("b : " + b);
    }
}

输入:
aa aa
aa
输出:
a : aa
b : aa aa

Process finished with exit code 0
复制代码

转载于:https://juejin.im/post/5cb95ac26fb9a0688f37658b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值