【问题标题】:reading txt file into 2d array java将txt文件读入二维数组java
【发布时间】:2016-04-30 16:01:01
【问题描述】:

Java 的初学者。我的程序只打印一个长列而不是二维数组。为了测试,我使用了一个 10 行 20 列的文件,但实际文件将是 20 列和几千行,我不知道有多少。我已经阅读了我在互联网上可以找到的关于这个主题的所有帖子,但仍然无法让程序运行。有什么想法吗?

 1 2 4 6 9 13 15 16 21 28 34 37 41 48 50 52 53 54 57 68
 6 7 10 17 23 24 27 28 31 39 42 43 46 48 50 55 60 61 67 70
 2 3 5 7 11 14 15 20 28 45 46 47 48 52 56 61 62 63 66 70
 4 5 7 11 13 15 19 23 24 27 28 35 38 40 48 50 57 58 64 66
 3 8 20 26 27 32 36 38 39 43 45 47 50 53 54 56 59 61 67 68
 1 3 5 7 15 19 26 30 31 36 41 44 48 49 56 58 59 60 61 65
 1 2 4 6 9 13 15 16 21 28 34 37 41 48 50 52 53 54 57 68
 6 7 10 17 23 24 27 28 31 39 42 43 46 48 50 55 60 61 67 70
 2 3 5 7 11 14 15 20 28 45 46 47 48 52 56 61 62 63 66 70
 4 5 7 11 13 15 19 23 24 27 28 35 38 40 48 50 57 58 64 66

这里是代码

try {
    FileInputStream fstream = new FileInputStream("C:\\keno.txt");

    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine = "";
    String[] tokens;

    //Read File Line By Line
    int row = 0;
    String userdata [][]= new String [10][21];
    while ((strLine = br.readLine()) != null)   {
        // Copy the content into the array
        tokens = strLine.split(" +");
        for(int j = 0; j < tokens.length; j++) {
            userdata[row][j] = tokens[j];
        }
        row++;
    }
    for(int i = 0; i < userdata.length; i++) {
        for(int j=0; j < userdata[i].length; j++){
            System.out.println(userdata[i][j]);
        }  
    }   
    in.close();
} catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
}

【问题讨论】:

  • "Any ideas?" -- 将大问题分解为更小的步骤,包括读取文本文件、解析一行文本、创建数组等,然后返回更具体和更易回答的问题问题是否停留在这些步骤之一。 "I've read all the posts I could find on the internet on this topic but still couldn't get the program to work."——你还没有向我们展示什么对你不起作用,没有这个,我们怎么能帮忙?请向我们展示您的相关代码和任何不当行为的描述。投票结束,等待您发布此重要信息。
  • 试图发布代码,网站不允许我。
  • 阅读网站返回给您的消息——您需要发布的不仅仅是代码,您还需要以文本形式发布有关代码应该做什么的大量信息。也不要在链接中发布代码或发布太多代码。您需要创建并发布minimal reproducible example,这通常意味着为此目的创建一个单独的小程序。
  • @hovercraft-full-of-eels:如果这个网站对用户友好,我会在 40 分钟前发布我的代码。

标签: java arrays 2d


【解决方案1】:


我写了一个简短的程序来做我认为你想做的事情。我的代码首先将所有数据从 txt 文件提取到一个字符串数组,然后用分隔符“”(空格)分割每个字符串。最后,字符串被解析为长格式。希望这可以帮助你。
重要提示:txt 文件必须具有相同的尺寸,这意味着如果第一行有 20 个元素,则每行必须有 20 个元素。 AND:每一行必须以一个元素结尾,而不是空格。让我知道这是否有帮助,如果没有,您在哪里遇到了麻烦!
打招呼

import java.io.*;
import java.util.ArrayList;

public class ReadFileInto2dArray{

    public static void main(String[] arg) throws FileNotFoundException, IOException, NumberFormatException {

        // IMPORT DATA FROM TXT FILE AS STRINGARRAY
        String filedirectory = "C:\\Users\\thomas\\Desktop\\Neuer Ordner\\keno.txt";
        BufferedReader b = new BufferedReader(new FileReader(filedirectory));
        String str=null;
        ArrayList<String> lines = new ArrayList<String>();
        while((str = b.readLine()) != null){
            lines.add(str);
        }
        String[] strArr = lines.toArray(new String[lines.size()]);  
        b.close();

        // GET DIMENSIONS: number of rows       
        int nRows = strArr.length;                                                                          
        // GET DIMENSIONS: number of elements in the first line
        int nCols = (strArr[0].length()-strArr[0].replace(" ", "").length())+1;     

        // INITIALIZE LONG 2D ARRAY (MATRIX)
        long[][] data = new long[nRows][nCols];

        // SPLIT EACH STRING OF ROW INTO SUBSTRING AND PARSE TO LONG FORMAT
        String[] split = new String[nCols];
        for (int r=0; r<nRows; r++){
            split = strArr[r].split(" ");
            for (int c=0; c<nCols; c++) {
                data[r][c] = Long.parseLong(split[c]);
            }
        }
        b.close();

        // SHOW THAT IT WORKED
        System.out.println("first element: data[0][0] should be 1: " + data[0][0]);
        System.out.println("last element data[9][19] should be 66: " + data[9][19]);

    }
}

【讨论】:

  • 它给了我一个错误“线程“main”中的异常 java.lang.NumberFormatException:对于输入字符串:“”
  • 和其他一些:在 java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 在 java.lang.Long.parseLong(Long.java:601) 在 java.lang.Long。 parseLong(Long.java:631)。你使用 Netbeans 吗?
  • 我用过eclipse!但我发现了错误,我忘了抛出一个异常,现在它已修复(我更新了代码)!当您根本不使用任何 IDE 并且只需在 cmd 窗口中编译它时,它就可以工作。重要提示:如果您使用 mac,则“filedirectory”字符串必须用“/”而不是“\\”分隔文件夹。希望它现在有效,让我知道。
  • 我在命令提示符下运行程序,它给了我与 Netbeans 相同的错误
  • 有人想解决这个问题吗?
猜你喜欢
  • 2012-09-17
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多