Reading from file double value using Scanner - InputMismatchException?

走远了吗. 提交于 2019-12-13 04:31:16

问题


I tried read from file double values and using Scanner with this aim.

It throws InputMismatchException :

"input.txt"  java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextDouble(Scanner.java:2456)

And I can't understand why this happen?

Code:

public class Largest
{
    public static void main(String[] args)
    throws FileNotFoundException
    {
        String filename = "input.txt"; 
        Scanner in = new Scanner(filename);

        double largest = in.nextDouble();
        while (in.hasNextDouble())
        {
            double input = in.nextDouble();
            if (input > largest)
            {
                largest = input;
            }
        }
        in.close();
        System.out.println("Largest value: " + largest);
    }
}

UPDATE:
I tried change double largest = in.nextDouble(); to double largest = 0;
But it get wrong input:

filename     Actual              Expected
-------------------------------------------------------------
"input.txt"  Largest value: 0.0  Largest value: 1.343239923E9
"input2.txt" Largest value: 0.0  Largest value: 40.1   

File content is like this:

89343455
46746846
56.78
55486411

How to solve this trouble?


回答1:


I found solution - need to create File object and then feed it to scanner class:

String filename = "input.txt"; 
File newFile = new File(filename);
Scanner in = new Scanner(newFile);



回答2:


Try this

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner;

public class MainClass{
public static void main(String[] args)
        throws FileNotFoundException
{
    Scanner in = new Scanner(new File("D:\\input.txt"));
    String largestNum=in.next().trim();
    double largest = Double.parseDouble(largestNum);
    while (in.hasNextDouble())
    {
        String Num=in.next().trim();
        double input = Double.parseDouble(Num);
        if (input > largest)
        {
            largest = input;
        }
    }
    in.close();
    System.out.println("Largest value: " + largest);
} }



回答3:


  • Initialise largest to the first double (after checking the type)
  • Use the correct delimiter to parse your input (\n = newline)

    String filename = "input.txt"; 
    Scanner in = new Scanner(filename).useDelimiter("\\n");
    
    double largest;
    if (in.hasNextDouble())
        largest = in.nextDouble();
    
    while (in.hasNextDouble())
    {
        double input = in.nextDouble();
        if (input > largest)
        {
            largest = input;
        }
    }
    


来源:https://stackoverflow.com/questions/17407370/reading-from-file-double-value-using-scanner-inputmismatchexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!