只阅读双打不起作用

Eri*_*rik 1 java double

我在从txt文件中读取double值时遇到问题.我的程序只将int转换成双打,但我想忽略它们.

示例文件:

1 2 3 4.5
5 6 7 8.1
9 10 11 12.7
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

File file = new File("file.txt");

    try{
        Scanner scanner = new Scanner(file);
        scanner.useLocale(Locale.US);
        while (scanner.hasNextLine()){
            if (scanner.hasNext() && scanner.hasNextDouble()){
                double value = scanner.nextDouble();
                System.out.println(value);
            }
        }
    }catch(FileNotFoundException e){}
Run Code Online (Sandbox Code Playgroud)

我的输出是:

1.0
2.0
3.0
4.5
5.0
6.0
7.0
8.1
9.0
10.0
11.0
12.7
Run Code Online (Sandbox Code Playgroud)

Hen*_*ter 7

好吧,整数可以表示为双打,所以Scanner当你要求它找到双打时,它会被捡起来.您必须在扫描后手动检查整数值,否则用于Scanner.nextInt跳过整数输入,仅nextDouble在您(暂时)用完整数时使用.所以你的循环中的条件看起来像这样:

if (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        scanner.nextInt(); // Ignore this value since it's an Integer
    } else if (scanner.hasNextDouble()){
        double value = scanner.nextDouble();
        System.out.println(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然说实话,但我有点困惑,为什么你使用循环hasNextLine()的条件while,因为这需要你单独检查hasNext(),就像你现在做的那样.为什么不这样做呢?

while (scanner.hasNext()) { // Loop over all tokens in the Scanner.
    if (scanner.hasNextInt()) {
        scanner.nextInt(); // Ignore this value since it's an Integer
    } else if (scanner.hasNextDouble()){
        double value = scanner.nextDouble();
        System.out.println(value);
    }
}
Run Code Online (Sandbox Code Playgroud)