I need to write a program that reads and stores an inputted file in Java in a double array. The number of values in the file is stored in the first line of the file, then the actual data values follow.
Here is what I have 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();
}
Input File is as follows:
10
43628.45
36584.94
76583.47
36585.34
86736.45
46382.50
34853.02
46378.43
34759.42
37658.32
As of now, regardless of the file name I input, I am getting 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)
                new Scanner(String) constructor scans the specified String. Not the file denoted by the pathname in the string.
If you want to scan the file, use
Scanner in = new Scanner(new File(inputFileName));
                        Check the following code. Scanner must be provided with File instead of just String as shown in the following 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:
Please enter the name of the input file: c:/hadoop/sample.txt
43628.45
36584.94
76583.47
36585.34
86736.45
46382.5
34853.02
46378.43
34759.42
37658.32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With