关于nextLine()和next()的使用,区别
来源:互联网 发布:如何查淘宝搜索热度 编辑:程序博客网 时间:2024/05/29 19:40
next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。简单地说,next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next方法不能得到带空格的字符串。
鉴于以上两种方法的只要区别,同学们一定要注意next()方法和nextLine(0方法的连用,下面举个例子来说明:
import java.util.Scanner;public class NextTest { public static void main(String[] args) { // TODO Auto-generated method stub String s1,s2; Scanner sc=new Scanner(System.in); System.out.print("请输入第一个字符串:"); s1=sc.nextLine(); System.out.print("请输入第二个字符串:"); s2=sc.next(); System.out.println("输入的字符串是:"+s1+" "+s2); }}
运行结果:
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home
但如果把程序改一下,
运行结果是:
请输入第一个字符串:home
请输入第二个字符串:输入的字符串是:home
可以看到,nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法给s2从键盘输入值。经过验证,我发现其他的next的方法,如double nextDouble()
import java.util.Scanner;public class NextTest { public static void main(String[] args) { // TODO Auto-generated method stub String s1,s2; Scanner sc=new Scanner(System.in); System.out.print("请输入第一个字符串:"); s1=sc.next(); sc.nextLine(); System.out.print("请输入第二个字符串:"); s2=sc.nextLine(); System.out.println("输入的字符串是:"+s1+" "+s2); }}
运行结果是:
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home
- 关于nextLine()和next()的使用,区别
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用
- 关于nextLine()和next()的使用
- next() 和 nextLine() 的 区别
- Scanner中next()和nextLine()方法的区别
- Java中.next()和.nextLine()的区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- next()和nextline()的区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- next和nextLine的区别
- next和nextLine的区别
- next()和nextLine()的区别
- next()和nextLine()的区别
- code forces 397B On Corruption and Numbers
- Linux的10个经典彩蛋
- WebService基础
- c++ oc
- Android_Service组件详解
- 关于nextLine()和next()的使用,区别
- Gas Station
- openURL的使用方法:
- 在grep和sed中用到的简单正则表达式
- IntelliJ IDEA 快捷键大全
- Android_BroadcastReceiver广播接收者详解及应用
- servlet
- 丁老师的作业,书上的代码
- Path Sum II