简体   繁体   中英

Reading only Doubles don't work

I have a problem reading double values from txt file. My program only converts ints to doubles, but i want to ignore them.

Example file:

1 2 3 4.5
5 6 7 8.1
9 10 11 12.7

Here is my code:

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){}

My output is:

1.0
2.0
3.0
4.5
5.0
6.0
7.0
8.1
9.0
10.0
11.0
12.7

Well, Integers can be represented as Doubles, so Scanner will pick them up when you ask it to find Doubles. You'll have to either check for Integer values manually after you scan them in, or else use Scanner.nextInt to skip over integer inputs and only use nextDouble when you (temporarily) run out of Integers. So your conditional inside your loop would look something like this:

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);
    }
}

Although to be perfectly honest, I'm a little confused why you're using hasNextLine() as the condition for your while loop, since this requires you to check separately for hasNext() , as you're doing now. Why not just do this?

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);
    }
}

好吧,然后使用.hasNextInt()检查它是否具有整数作为下一个标记

Try this...

if (scanner.hasNext()) {
        double value = scanner.nextDouble(); // Ignore this value since it's an Integer
        if (!value.toString().endsWith(".0"))
             System.out.println(value);
    }
}

It will break if you're not using standard numerals, but I'm not aware of any places that aren't. The reason for your error is that java converts int to double implicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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