Java Scanner类学习1:Next()与nextLine()
Scnner类是一种输入方法,但是在实际使用过程中,next()、nextInt()、next Lin()e等等读取方式有些差异。因此,这里对此展开探索。
1.同一方法中next()和nextLine()
首先研究next()和nextLine():
import java.util.*;
public class ScanLearn1
{
public static void main(String[] args)
{
final int COUNT = 4;
Scanner reader = new Scanner(System.in);
Object[] a = new Object[COUNT];
a[0] = reader.next();
a[1] = reader.nextLine();
a[2] = reader.next();
a[3] = reader.nextLine();
for (Object b : a) System.out.println(b);
reader.close();
}
}
遇到有效字符后:
遇到有效字符前:
小小的修改程序:
a[0] = reader.next();
a[1] = reader.next();
a[2] = reader.nextLine();
a[3] = reader.nextLine();
从结果上来看,next()有如下特点:
1)遇到有效字符前的空白(空格、Tab、回车)均不识别;
2)遇到有效字符后的空白结束读取,并且空白不会被读入,换言之,next()只读取它遇到的首个不含空白有效字符部分。
nextLine()则有以下特点:
1)读取所有内容,直到遇到回车;
2)如果上一个方法有没读入的空白,nextLine()会读入这些空白,如果这些空白含回车,这从第一个回车开始结束。
由于next()和nextLine有这样的特点,当next()与nextLine()连用时就会出现nextLine()只读到回车引发一系列连锁问题。
一种可行的方法的是专门加一个nextLine()吸收之前操作产生的回车,但前提是前面只有一个多余的回车。
nextInt()、nextFloat()等特点则与next()类似,故不再叙述。
2.不同方法/类中的Scanner类
在实际使用中,scanner类更多使用在main()方法以外,那些方法也很可能不只一个,所以这里对第一步的程序进行修改以初步了解多方法使用Scanner类:
import java.util.*;
public class ScanLearn1
{
public static void main(String[] args)
{
final int COUNT = 3;
Scanner reader = new Scanner(System.in);
Object[] a = new Object[COUNT];
a[0] = reader.next();
a[1] = A.setA();
a[2] = reader.nextLine();
for (Object b : a) System.out.println(b+",");
reader.close();
}
}
class A
{
static Object setA()
{
Scanner reader = new Scanner(System.in);
Object aaa = reader.nextLine();
reader.close();
return aaa;
}
}
从结果上来看,不同的方法里使用的Scanner毫无关系,他们各自独立地使用各自的数据。比如这里main方法的a[0]和a[2]就1(空格)(回车)进行了操作,A类的setA方法则操作了2(空格)(回车)。
不同方法(同类)的经过检验,效果相同