将文本文件放入 Java 中的二维不规则数组 [英] Getting a text file into a two dimensional ragged array in Java

查看:25
本文介绍了将文本文件放入 Java 中的二维不规则数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,这是对 我以前的问题.我现在有一个格式如下的文本文件:

Hey guys this is a followup to my previous question. I now have a text file which is formatted like this:

100 200
123
124 123 145

我想要做的是将这些值放入 Java 中的二维不规则数组中.到目前为止,我所拥有的是:

What I want to do is get these values into a two dimensional ragged array in Java. What I have so far is this:

public String[][] readFile(String fileName) throws FileNotFoundException, IOException {
       String line = "";
       ArrayList rows = new ArrayList();


       FileReader fr = new FileReader(fileName);
       BufferedReader br = new BufferedReader(fr);

       while((line = br.readLine()) != null) {
        String[] theline = line.split("\\s");//TODO: Here it adds the space between two numbers as an element
        rows.add(theline);
       }
       String[][] data = new String[rows.size()][];
       data = (String[][])rows.toArray(data);
       //In the end I want to return an int[][] this a placeholder for testing
       return data;

我的问题是,例如,对于第 100 200 行,变量theline"具有三个元素 {"100","","200"} 然后它传递给行rows.add(theline)我想要的是只有数字,如果可能的话,如何将此 String[][] 数组转换为 int[][] 数组 int 以返回它.谢谢!

My problem here is that for example for the line 100 200 the variable "theline" has three elements {"100","","200"} which it then passes on to rows with rows.add(theline) What I want is to have just the numbers and if possible how to convert this String[][] array into an int[][] array int the end to return it. Thanks!

推荐答案

好的,这是基于 Gonzo 建议的解决方案:

OK this is a solution based on what Gonzo suggested:

public int[][] readFile(String fileName) throws FileNotFoundException, IOException {
   String line = "";
   ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();


   FileReader fr = new FileReader(fileName);
   BufferedReader br = new BufferedReader(fr);

   int r = 0, c = 0;//Read the file
   while((line = br.readLine()) != null) {
       Scanner scanner = new Scanner(line);
       list.add(new ArrayList<Integer>());
       while(scanner.hasNext()){

           list.get(r).add(scanner.nextInt());
           c++;
       }
       r++;
   }

   //Convert the list into an int[][]
   int[][] data = new int[list.size()][];
   for (int i=0;i<list.size();i++){
       data[i] = new int[list.get(i).size()];
      for(int j=0;j<list.get(i).size();j++){
          data[i][j] =  (list.get(i).get(j));
      }


   }
   return data;
}

这篇关于将文本文件放入 Java 中的二维不规则数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆