Scanner中next,nextInt,nextLine的区别

Scanner的本质是依赖于正则表达式的,他会将扫描的数据放在缓冲区中,根据空格符进行匹配区分。
1)next() 会自动过滤空格、tab、enter等结束符,直至遇到有效字符之后,空格、tab、enter等会视为结束符
2)nextLine() 读取到回车才结束
3)nextInt() 只读取数值,回车会被存在缓冲区中

		Scanner sc = new Scanner(System.in);
		
		//==========================================
		System.out.println("输入:nextInt");
		int arr = sc.nextInt();
		//===================================
		System.out.println("输入:next");
		String str = sc.next();
		//===================================
		System.out.println("输入:nextLine");
		String str1 = sc.nextLine();
		

输出结果:

输入:nextInt
111
输入:next
  
   tfgyhjuk
输入:nextLine

next()和nextInt()的结束符都会存再缓存中,当我们在他们后面使用nextLine()时,nextLine()会自动读取缓存中的回车符,然后结束读取任务,所以nextLine()并不是没有执行。
为了避免这种事情,我们可以这样使用下面这种情况。

		System.out.println("输入:nextInt");
		int arr = sc.nextInt();
		sc.nextLine();   //读取上个nextInt留下的回车符
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
nextLine() 方法用于读取输入的一行文本,包括空格和特殊字符。该方法返回一个字符串,以换行符(\n)结尾。 例如,以下代码将读取用户输入的一行文本: ``` import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入一行文本:"); String str = sc.nextLine(); System.out.println("您输入的是:" + str); } } ``` 如果用户输入了文本 "Hello World",则输出结果如下: ``` 请输入一行文本:Hello World 您输入的是:Hello World ``` next() 方法用于读取输入的下一个字符串,直到遇到空格或特殊字符为止。该方法返回一个字符串,不包括空格和特殊字符。 例如,以下代码将读取用户输入的一个字符串: ``` import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入一个字符串:"); String str = sc.next(); System.out.println("您输入的是:" + str); } } ``` 如果用户输入了字符串 "Hello World",则输出结果如下: ``` 请输入一个字符串:Hello World 您输入的是:Hello ``` nextLine() 方法和 next() 方法的区别在于,nextLine() 方法会读取包括空格和特殊字符在内的整行文本,而 next() 方法只会读取下一个字符串,直到遇到空格或特殊字符为止。因此,如果想读取包含空格的字符串,应该使用 nextLine() 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清清兀商

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值