java中扫描仪关闭语句_关于Java中扫描仪next()与nextLine()的区别

首先,next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。

简单地说,next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next()方法不能得到带空格的字符串。

而nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。

记得有个博客上有一句话(next()是我只要文字,而nextLine()是啥我都要)

实例1:

public class H_Z03 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("输入s:");

String s = in.nextLine();

System.out.println("输入s1");

String s1 = in.next();

System.out.println(s);

System.out.println(s1);

}

}

输出结果:

输入s:

张三

输入s1

李四

张三

李四

这个结果是输入正常,显示也正常的。

示例2

public class H_Z04 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("输入s:");

String s = in.next();

System.out.println("输入s1");

String s1 = in.nextLine();

System.out.println(s);

System.out.println(s1);

}

}

输入输出结果:

输入s:

张三

输入s1

张三

这个出现了问题只让输入“张三”,

查询相关资料发现:

String s1 = in.nextLine();

接受空格之后的字符(包括回车、空格、空格之后的字符)

测试结果如下:

public class H_Z05 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("输入s:");

String s = in.next();

System.out.println("输入s1");

String s1 = in.nextLine();

System.out.println(s);

System.out.println(s1);

}

}

输入输出结果:

输入s:

张三 李四

输入s1

张三

李四

总结:

nextLine()会自动接收next()之后的字符,但是这个指的是对同一个对象。

解决方法:

public class H_Z06 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("输入s:");

String s = in.next();

System.out.println("输入s1");

in.nextLine();

String s1 = in.nextLine();

System.out.println(s);

System.out.println(s1);

}

}

输入输出结果:

输入s:

张三 李四

输入s1

王五

张三

王五

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值