Scanner 中next()和nexline()方法的区别

 
在java实现字符窗口的输入时,很多人更喜欢选择使用扫描器scanner,它操作起来比较简单。在编程的过程中,我发现用scanner实现字符串的输入有两种方法,一种是next(),另一种是nextline(),这两种有以下区别:
1. next()一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、tab键或enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、tab键或enter键等视为分隔符或结束符。
2.  简单地说,next()查找并返回来自此扫描器的下一个完整标记。完整标记的前后是与分隔模式匹配的输入信息,所以next方法不能得到带空格的字符串。
3. nextline()方法的结束符只是enter键,即nextline()方法返回的是enter键之前的所有字符,它是可以得到带空格的字符串的。
下面介绍使用方法的例子:
import port java.util.scanner;  
public class nexttest{  
    public static void main(string[] args) {  
        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);  
    }  
}  
运行结果:
请输入第一个字符串:hello
请输入第二个字符串:world

输入的字符串是:hello world


把程序改一下:
import port java.util.scanner;  
public class nexttest{  
    public static void main(string[] args) {  
        string s1,s2;  
        scanner sc=new scanner(system.in);  
        system.out.print("请输入第一个字符串:");  
        s1=sc.next();  
        system.out.print("请输入第二个字符串:");  
        s2=sc.nextline();  
        system.out.println("输入的字符串是:"+s1+" "+s2);  
    }  
}  
运行结果是:
请输入第一个字符串:hello
请输入第二个字符串:输入的字符串是:hello


 可以看到,nextline()自动读取了被next()去掉的enter作为他的结束符,所以没办法给s2从键盘输入值。经过验证,我发现其他的next的方法,如double nextdouble() , float nextfloat() , int nextint() 等与nextline()连用时都存在这个问题,解决的办法是:在每一个 next()、nextdouble() 、 nextfloat()、nextint() 等语句之后加一个nextline()语句,将被next()去掉的enter结束符过滤掉。

import port java.util.scanner;  
public class nexttest{  
    public static void main(string[] args) {  
        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);  
    }  
}  


运行结果是:
请输入第一个字符串:hello
请输入第二个字符串:world
输入的字符串是:hello world

猜你喜欢

转载自www.cnblogs.com/zhaoyuan72/p/10932654.html
今日推荐