java Scanner中的hasNext()方法

时间:2023-02-04 05:48:10

hasNext()方法判断输入(文件、字符串、键盘等输入流)是否还有下一个输入项,若有,返回true,反之false。

Scanner sc = new Scanner(new File("test.txt"));

System.out.println(sc.hasNext());

若test.txt为空(空格、tab、回车),则输出结果为false;若该文件不为空输出true。

当输入为键盘时,该方法出现阻塞(block),也即等待键盘输入。输入源没有结束,又读不到更多输入项。

		Scanner sc = new Scanner(System.in);

		System.out.println(sc.hasNext());

运行上面的程序,控制台等待键盘输入,输入信息后输出结果为true。

输入:Hello
true

由上面的知识,则如下代码则不难理解:

		Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println("Input from keyboard:" + sc.next());
}

sc.hasNext()始终等待键盘输入,输入信息后,sc.next()打印出该信息。