简体   繁体   English

Java - 如何使用扫描仪将文本文件的值存储到数组中?

[英]Java - How to store values of a text file into an array using Scanner?

import java.io.*;

import java.util.*;

import java.text.*;

public class textFile {

    public static void main(String args[]) throws IOException {

        Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt"));
        int maxIndx = -1;
        String text[] = new String[1000];
        while (sf.hasNext()) {
            maxIndx++;
            text[maxIndx] = sf.nextLine();
        }

        sf.close();

        double average[] = new double[100];

        for (int j = 0; j <= maxIndx; j++) {
            Scanner sc = new Scanner(text[j]);
            int k = 0;
            while (k <= 10) { //attempt to store all the values of text file (DataGym.in.txt) into the array average[] using Scanner
                average[k] = sc.nextDouble();
                k++;
            }
        }
    }
}

My code doesn't work and keeps giving me this error at the place where I store sc.nextDouble() into the k element of the array:我的代码不起作用,并在我将 sc.nextDouble() 存储到数组的 k 元素的位置不断给我这个错误:

java.util.NoSuchElementException: java.util.NoSuchElementException:

null (in java.util.Scanner) null(在 java.util.Scanner 中)

You should check out the Scanner API .您应该查看Scanner API It is suspicious that you have a call to Scanner.hasNext() with a following call to Scanner.nextLine() .可疑的是,您调用Scanner.hasNext()并随后调用Scanner.nextLine() There are complimentary calls to check and then get from a Scanner .有免费电话检查,然后从Scanner获得。 For instance if you really want the next line then you should check if Scanner.hasNextLine() before calling Scanner.nextLine() .举例来说,如果你真的想下一行,那么你应该检查是否Scanner.hasNextLine()调用之前Scanner.nextLine() Similarly you call Scanner.nextDouble() without preceding it with a call to Scanner.hasNextDouble() .类似地,您在调用Scanner.nextDouble()之前没有调用Scanner.hasNextDouble()

Also like some of the comments mention you should use a debugger or print statements to see if you are getting what you expect you should be getting.也像一些评论提到的那样,您应该使用调试器或打印语句来查看您是否得到了您期望的结果。 Steps like this are necessary to debugging.像这样的步骤是调试所必需的。

For instance after sf.close you could use System.out.println(Arrays.toString(text)) and judge if the array contains what you expect.例如,在sf.close之后,您可以使用System.out.println(Arrays.toString(text))并判断数组是否包含您期望的内容。

Hope this helps your debugging.希望这有助于您的调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM