Java中Scanner的next和nextLine的使用以及区别

来源:互联网 发布:php curl header 设置 编辑:程序博客网 时间:2024/06/05 00:48

Scanner实现字符串的输入的两种方法:一是next(),另一种则是nextLine(),下面通过代码实例看看两者的区别:

package SwordOffer;import java.util.Scanner;/** * Created by L_kanglin on 2017/3/14. * 区分next和nextLine */public class TestNextAndNextLine {    public static void main(String[] args){        Scanner sc=new Scanner(System.in);        TestNextLine(sc);    }    public static void TestNext(Scanner sc){        String str1=sc.next();        System.out.println("str1:"+str1);    }    public static void TestNextLine(Scanner sc){        String str2=sc.nextLine();        System.out.println("str2:" +str2);    }}

next的测试:

abc defstr1:abc

nextLine的测试:

abc defstr2:abc def

由上述的结果,可以得到:
next()对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或者结束符,所以next()方法读取的是不能带空格的字符串。
nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。

注意一下情况,就是两者一起用:

import java.util.Scanner;/** * Created by L_kanglin on 2017/3/14. * 区分next和nextLine */public class TestNextAndNextLine {    public static void main(String[] args){        Scanner sc=new Scanner(System.in);        TestNext(sc);    }    public static void TestNext(Scanner sc){        String str1=sc.next();        String str3=sc.nextLine();        System.out.println("str1:"+str1);        System.out.println("str3:"+str3);    }    public static void TestNextLine(Scanner sc){        String str2=sc.nextLine();        System.out.println("str2:" +str2);    }}

测试如下:

abc defstr1:abcstr3: def

此时str3的是接上一个输入值来的,使用nextLine,可以读取空格值。

0 0
原创粉丝点击