简体   繁体   中英

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.

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. Also I suppose you should reset the pointer of the scanner after counting the rows. ArrayList should be more useful for your goal.

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). We then use ArrayList like so:

public static void main (String[] args) throws 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.

Maroun is right, you really need to use some Collections to help you with that :

 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 :

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);

But as per answers above, we suggest change the code to use array lists if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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