简体   繁体   English

.hasNext()不会变成假

[英].hasNext() wont turn false

I have the following code and I cannot understand why .hasNext() wont turn false. 我有以下代码,但我不明白为什么.hasNext()不会变为假。 I am reading from a file called test. 我正在从一个名为test的文件中读取。

My code: 我的代码:

package printing;
import java.io.File;
import java.util.Scanner;

public class Printer {
    public int count() throws Exception{
        int num = 0;
        File f = new File("C:\\Users\\bob\\Desktop\\test.txt");
        Scanner in = new Scanner(f);
        while (in.hasNext()){
            num++;
        }
        return num;
    }
}

Main: 主要:

public class Main {
    public static void main(String[] args) throws Exception{
        Printer mine = new Printer();
        System.out.println(mine.count());
    }
}

File content: 档案内容:

4 4 6 3 8 8 8 4 4 6 3 8 8 8

What is wrong? 怎么了?

You need to consume the input from the Scanner 您需要使用扫描仪的输入

while (in.hasNext()){
    in.next();
    num++;
}

You didn't consume any of the input. 您没有消耗任何输入。 hasNext() doesn't consume any input. hasNext()不消耗任何输入。

The scanner does not advance past any input. 扫描仪不会前进超过任何输入。

Add a call to next() inside the while loop to consume the input. while循环内添加对next()的调用以使用输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM