java中Scanner类nextLine()和next()的区别和使用方法

来源:互联网 发布:东华软件待遇怎么样 编辑:程序博客网 时间:2024/06/05 06:49

在实现字符窗口的输入时,很多人更喜欢选择使用扫描器Scanner,它操作起来比较简单。在编程的过程中,我发现用Scanner实现字符串的输入有两种方法,一种是next(),一种nextLine(),但是这两种方法究竟有什么区别呢?

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

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

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

鉴于以上两种方法的只要区别,一定要注意next()方法和nextLine()方法的连用,举个例子:

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);      }  }  

运行结果:
请输入第一个字符串:home
请输入第二个字符串:work

输入的字符串是:home work

但如果把程序改一下:

public class Test1 {public static void main(String[] args) {        String s1,s2;          Scanner sc=new Scanner(System.in);          s1=sc.next();          s2=sc.nextLine();         System.out.println("输入的字符串是:"+s1+" "+s2);      }  }
运行的结果是只能输入一个home,就无法继续输入第二个字符串

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

public class Test1 {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.next();          sc.nextLine();        System.out.println("输入的字符串是:"+s1+" "+s2);    }  }
运行结果是:
请输入第一个字符串:home
请输入第二个字符串:work
输入的字符串是:home work



阅读全文
0 0
原创粉丝点击