java – 以双数组的形式读取和存储文件内容

前端之家收集整理的这篇文章主要介绍了java – 以双数组的形式读取和存储文件内容前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要编写一个程序,用 Java中的双数组读取和存储输入的文件.文件中的值数存储在文件的第一行,然后是实际数据值.

这是我到目前为止:

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

输入文件如下:

10
43628.45
36584.94
76583.47
36585.34
86736.45
46382.50
34853.02
46378.43
34759.42
37658.32

截至目前,无论我输入的文件名是什么,我都收到一条异常消息:

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)

解决方法

请检查以下代码.扫描程序必须提供File而不是String,如下面的代码段所示:
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();
    }
}

样本输出

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

猜你在找的Java相关文章