加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:43:09 所属栏目:Java 来源:网络整理
导读:我需要编写一个程序,用 Java中的双数组读取和存储输入的文件.文件中的值数存储在文件的第一行,然后是实际数据值. 这是我到目前为止: public static void main(String[] args) throws FileNotFoundException{ Scanner console = new Scanner(System.in); Sys
我需要编写一个程序,用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读