Java中Scanner类next()和nextLine()方法辨析

next()方法使用:

我们知道,next()方法在读取到空白符(Space键 , enter键 , tab键)时就结束,但这是有前提的:即next()方法一定要读取到有效字符后才可以结束. 如果在有效字符之前录入了空白符的话,next()方法会将这些空白符"过滤"掉,直接从有效字符开始读取. 举个例子:

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一句话:");
        String str=sc.next();
        System.out.println(str);
        sc.close();
    }
}

运行结果如下图:
在这里插入图片描述
可以看到,即使你在输入有效字符之前狂按tab键或enter键或space键,next()方法还是从有效字符之处开始读取!
当next()方法读取到有效字符之后,倘若再出现空白符的话,next()就将其视作结束符.

nextLine()方法使用:

我们知道,nextLine()方法的结束符只是enter键,所以用它来读取录入数据的话是可以得到带有空格的字符串的.

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一句话:");
        String str=sc.nextLine();
        System.out.println(str);
        sc.close();
    }
}

在这里插入图片描述
另外值得注意的是:nextLine()方法返回的是enter键之前所有的字符,包括空字符.

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一句话:");
        String str=sc.nextLine();
        System.out.print(str);
        sc.close();
    }
}

在这里插入图片描述
可以看到,我们在键盘上什么都不录入,直接敲enter键,可以看到nextLine()方法还有能读取且输出.

总结

Scanner是一个扫描器,我们录入到键盘的数据,先存到缓存队列中等待读取.

next()方法在读取到有效字符之后,一看到空白符就立刻结束.(它不会读取空白符,也就不会将空白符从缓存队列中删掉)

nextLine()方法会读取enter键,一读到enter键方法就结束.它会将enter键从缓存队列中删除.nextLine()方法返回enter键之前的所有字符,包括空字符.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值