Java – reads and stores the contents of the file as a double array

I need to write a program to read and store input files with double arrays in Java The number of values in the file is stored in the first line of the file, followed by the actual data value

This is what I have done so far:

public static void main(String[] args) throws FileNotFoundException
{
    Scanner console = new Scanner(system.in);
    System.out.print("Please enter the name of the input file: ");
    String inputFileName = console.next();

    Scanner in = new Scanner(inputFileName);

    int n = in.nextInt();
    double[] array = new double[n];

    for( int i = 0; i < array.length; i++)
    {
        array[i] = in.nextDouble();
    }

    console.close();
}

The input file is as follows:

So far, no matter what the file name I entered, I have received an exception message:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(UnkNown Source)
    at java.util.Scanner.next(UnkNown Source)
    at java.util.Scanner.nextInt(UnkNown Source)
    at java.util.Scanner.nextInt(UnkNown Source)
    at Project6.main(Project.java:33)

Solution

Please check the following codes The scanner must provide a file instead of a string, as shown in the following code snippet:

public class Main {
    public static void main(String[] args) {
        Scanner console = new Scanner(system.in);
        System.out.print("Please enter the name of the input file: ");
        String inputFileName = console.nextLine();

        Scanner in = null;
        try {
            in = new Scanner(new File(inputFileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int n = in.nextInt();
        double[] array = new double[n];

        for (int i = 0; i < array.length; i++) {
            array[i] = in.nextDouble();
        }
        for (double d : array) {
            System.out.println(d); 
        }
        console.close();
    }
}

Sample output:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>