简体   繁体   English

JAVA从行数未知的文件填充2D数组

[英]JAVA Filling a 2D array from a file with an unknown amount of rows

I am trying to figure out how to make a program that reads data from a text file, and fills a Jtable with it, I will need to be able to search the table, and do some calculations with the numbers. 我试图弄清楚如何制作一个从文本文件中读取数据并用它填充Jtable的程序,我将需要能够搜索表并使用数字进行一些计算。

A row in the text file would contain: 文本文件中的一行将包含:

name, country, gender, age, weight

The number of rows is unknown (I need to count the number of rows). 行数是未知的(我需要计算行数)。 This is what I tried, but it seems to crash. 这是我尝试过的方法,但似乎崩溃了。 I need to count the # of rows, and then fill the array with the content from the rows . 我需要计算行数,然后将行中的内容填充到数组中

package Jone;
import java.io.*;
import java.util.*;


public class Jone  {
    public static void main (String [] args)throws IOException{
        int rows = 0;

        Scanner file = new Scanner (new File("data.txt"));
        while (file.hasNextLine()){rows++;}
        Object[][] data = new Object[rows][5];
        System.out.print(rows);
        file.nextLine();
        for(int i = 0;i<rows;i++)
        {
            String str = file.nextLine();
            String[] tokens= str.split(",");
            for (int j = 0;j<5;j++)
            {
                data[i][j] = tokens[j]; 

                System.out.print(data[i][j]);
                System.out.print(" ");
            }         
        }
        file.close();
    }
}

change your code as follows 如下更改代码

package Jone;
import java.io.*;
import java.util.*;


public class Jone  {
    public static void main (String [] args)throws IOException{
       try{
    int rows = 0;
    Scanner file = new Scanner (new File("data.txt"));
    while (file.hasNextLine())
    {
        rows++;
        file.nextLine();
    }

    file = new Scanner (new File("data.txt"));
    System.out.println(rows);
    Object[][] data = new Object[rows][5];
    for(int i = 0;i<rows;i++)
    {
        String str = file.nextLine();
        String[] tokens= str.split(",");
        for (int j = 0;j<5;j++)
        {
            data[i][j] = tokens[j]; 
            System.out.print(data[i][j]);
            System.out.print(" ");
        }         
    }
    file.close();
            }
    catch(Exception e)
    {
        e.printStackTrace();
    }

}

You create an array with 0 rows and then you try to access the empty array dimension. 您创建具有0行的数组,然后尝试访问空数组维。 Also I suppose you should reset the pointer of the scanner after counting the rows. 另外我想您应该在对行进行计数之后重置扫描仪的指针。 ArrayList should be more useful for your goal. ArrayList对于您的目标应该更有用。

class Person { 类人{

 String name, country, gender; int age; double weight; public Person(String n, String c, String g, int a, double w) { name = n; country = c; gender = g; age = a; weight = w; } 

} }

Would properly model your data better when you are extracting from the file (I took a guess at Person but call it what you will). 从文件中提取数据时,可以更好地正确建模数据(我猜过Person但称其为您想要的)。 We then use ArrayList like so: 然后,我们像这样使用ArrayList

public static void main (String[] args) throws IOException { 公共静态void主对象(String [] args)引发IOException {

  ArrayList<Person> people = new ArrayList<Person>(); Scanner file = new Scanner (new File("data.txt")); while (file.hasNextLine()) { String str = file.nextLine(); String[] tokens= str.split(","); people.add(new Person(tokens[0], tokens[1], tokens[2], Integer.parseInt(tokens[3], Double.parseDouble(tokens[4])))); } file.close(); Person[] arrayPeople = people.toArray(); 

} }

ArrayLists are far more powerful than arrays as you can perform all sorts of operations on them like sorts and searches and of course you don't have to worry about their initial size because they just grow as you add new elements. ArrayList比数组强大得多,因为您可以对它们执行各种操作,例如排序和搜索,当然,您不必担心它们的初始大小,因为它们会随着您添加新元素而增长。

Maroun is right, you really need to use some Collections to help you with that : Maroun是正确的,您确实需要使用一些Collections来帮助您:

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

    List<String[]> lines = readFiles(new File("data.txt"));
    String[][] data = lines.toArray(new String[0][]);
}

public static List<String[]> readFiles(File file) {
    List<String[]> data = new LinkedList<>();

    Scanner scanner = null;
    try {
        scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] tokens = line.split(",");
            data.add(tokens);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        scanner.close();
    }

    return data;
}

Note that you can use some third party libraries like Commons IO to read the file's lines : 请注意,您可以使用一些类似Commons IO的第三方库来读取文件的行:

List<String> lines = org.apache.commons.io.FileUtils.readLines(new File("data.txt"));)

Less code = less bugs! 更少的代码=更少的错误!

Hope it helps 希望能帮助到你

Move this line 移动这条线

Object[][] data = new Object[rows][5];

below System.out.print(rows); 在System.out.print(rows)下面;

But as per answers above, we suggest change the code to use array lists if possible. 但是按照上面的答案,我们建议尽可能更改代码以使用数组列表。

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

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