nextInt(),next()与nextLine()
Java中一般用next(),nextLine()以及nextInt(),nextDouble()获取字节流,那么她们以什么分割,读取对象是什么,互相之间又有什么区别呢?
先讲结论:
nextInt()取单个标记(一个整数),以空格回车制表符分割
next()取字符串,也是以空格回车制表符分割,一般常与hasNext()配合
NextLine()读取一行,注意到如果是一行的话,空格不作为分割符,一行一行的取,以回车(换行)结束一次取值。
区别:
next()不会吸取字符前/后的空格/Tab键,只吸取字符(忽略空格回车等等),开始吸取字符(字符前后不算)直到遇到空格/Tab键/回车截止吸取;
nextLine()吸取字符前后的空格/Tab键,直到回车键截止。
1:对于诸如nextInt(),nextDouble()而言,可以看出她们的返回值是int,double型,是单个的数,她们都是取流中一个数,默认情况下以空格,回车,Tab为分隔符。
她们取的值都是单个字符
Scanner sc = new Scanner(System.in); int i = sc.nextInt();//读取的整数数量 int index = 0; int[] array = new int [i];//存放读取的整数 while(index < i) { array[index++] = sc.nextInt(); } for (int num : array) {//输出读取整数 System.out.println("输入的整数:" + num); }
运行结果
2:next()
next()的对象是字符串,一般用hasNext()函数与之配合使用
Scanner sc =new Scanner(System.in); int i=sc.nextInt(); int index=0; String[] array=new String[i]; while(index<i) { array[index++]=sc.next(); } for(String str:array) { System.out.println("输入的整数:"+str); }
运行结果
可以看出和第一个差不多,除了是读入字符串之外,也是以回车,空格或者Tab为分割符。
2.1 next()与hasNext()的配合
Scanner sc = new Scanner(System.in); //判断sc中是否有下一个输入项,多个输入项以空格分开 while(sc.hasNext()) { String s = sc.next(); System.out.println(s); }
结果:
3:nextLine()
next()不会吸取字符前/后的空格/Tab键,只吸取字符,开始吸取字符(字符前后不算)直到遇到空格/Tab键/回车截止吸取;
nextLine()吸取字符前后的空格/Tab键,回车键截止。
注意看一下两个程序:
Scanner sc =new Scanner(System.in); int i=sc.nextInt(); int index=0; String [] array=new String[i]; while(index<i) { array[index++]=sc.nextLine(); } for(String str:array) { System.out.println("输入的字符串:"+str); }
结果:
原因在于,nextLine()将4后面的回车键当作一次输入
在4后面接空格不回车 就会得到正确结果
如果4后面跟着回车,该如何处理,我们可以先把没用的回车先吃掉,这样也能成功,只需要加上一句即可
Scanner sc =new Scanner(System.in); int i=sc.nextInt(); int index=0; String [] array=new String[i]; String enter=sc.nextLine();//吃掉多余的回车 while(index<i) { array[index++]=sc.nextLine(); } for(String str:array) { System.out.println("输入的字符串:"+str); }
运行结果