Java中Scanner包含一系列的next(),nextInt(),nextLong(),nextDouble(),nextLine()方法用于读取控制台用户的输入,但是这些方法是有一定区别的。方法next(),nextInt(),nextLong(),nextDouble()是令牌读取方法。当读取控制台输入的时候,这里以next()方法为例子,我们将它的分隔符设置为空格,例如:空格空格空格hello空格java,它们会跳过起始的三个空格然后读取字符串”hello”,然后遇到了空格,这个空格是不读取的,这时候一次next()方法执行完毕,讲这个字符串打印出来为:”hello”。并没有包含起始的三个空格和”hello”字符串后面的空格。`
public class Test{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
sc.useDelimiter(" ");
String s1 = sc.next();
System.out.println(s1);
}
}
这里输入为:java空格home
输出为:java
而nextLine()方法默认以换行符”\n”为分隔符,它会读取换行符之前的所有符号包括空格,最后这个换行符也会被读取,但是不会在nextLine()方法中返回。
public class Test{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s1 = sc.nextLine();
System.out.println(s1);
}
}
这里输入:空格空格空格java空格home
输出:空格空格空格java空格home
这里并没跳过字符串之前的空格和中间的空格,而是直接将这一行输入完整的输出了。
今天发现一个问题:
File file = new File("hello.txt");
Scanner in = new Scanner(file);
in.useDelimiter(" ");
while(in.hasNext()){
System.out.println(in.next());
}
我在hello.txt文件中输入空格空格空格hello world
结果又把前面的空格又输出了,同时world也输出了。这里就不懂了。
参考教材:java语言程序设计 基础篇