简体   繁体   中英

Creating a two dimensional array for a text file in java?

I have to import a text file containing both words and integers and then maintain the data using a two dimensional array. I can't seem to figure out how to make this array. The only imports I can use are Scanner, File, and FileNotFoundException. Here is the snippet of my code:

public static void DisplayInventory() throws FileNotFoundException
{

    try
    {
        Scanner autoInventory = new Scanner(new File("records.txt"));

        for (int Num = 0; Num < 15; Num++)
        {
            String autoRecords = autoInventory.nextLine();
            autoRecords = autoRecords.replace(';', ' ');
            System.out.println(autoRecords);

        }

    }
    catch (FileNotFoundException except)
    {
        System.out.println("Error: Inventory read failure. Error " +
            except.getMessage());
        System.exit(-1);

    }

}

As you can see, this does not show an array. I am unsure how to do this and have been at this for a few days now. I am a novice at java and this is an assignment. I appreciate any help you can give.

I am going to make a few assumptions (which might not be accurate). The first is that your file looks like this (a csv with 14 rows and 7 columns):

a1,b1,c1,d1,e1,f1,g1
a2,b2,c2,d2,e2,f2,g2
a3,b3,c3,d3,e3,f3,g3
a4,b4,c4,d4,e4,f4,g4
..

The next assumption is that your file contains values of type String . Before we do anything we need to declare the 2D array:

int numRecords = 14;
int numColumns = 7;
String[][] records = new String[numRecords][numColumns];

The code you posted attempts to read 15 lines from the Scanner, does a replace on ; (not sure what thats all about), and prints the line. This is a good start - this loop is responsible for reading each row. I would also add an additional condition that checks to see if there actually is a next line (use hasNextLine ).

for (int i = 0; i < numRecords && autoInventory.hasNextLine(); i++)
{
    String rowData = autoInventory.nextLine();
    String[] colData = rowData.split(",");

    for (int j=0; j<colData.length && j<numColumns; j++)
    {
        records[i][j] = colData[j];
    }
}

Inside this outer loop we start by collecting the rowData using nextLine . Next we use split (a function on String) to split the line into parts (delimited by , ), storing those parts in a 1D array. We declare a second loop (an inner loop) that loops over the colData - for each value we examine we place it into the appropriate position in the records array.

Now that the file has been read into the array, you can print it to the screen in a similar way. Use an outer loop (i) to iterate over the rows, and an inner loop (j) to iterate over the columns, printing out each records[i][j] .

for (int i=0; i<numRecords; i++) 
{
    for (int j=0; j<numColumns; j++) 
    {
        System.out.print(records[i][j]);

                                    // extra stuff..
        if (j != numColumns-1) {    // print commas between items if we want
            System.out.print(", ");
        }
    }
    System.out.println("");  // print out a newline after each row
}

I'm not entirely aware of what you're trying to do or why you need a two dimensional array, but here is how you would create both an array and a two-dimensional one, and how to add data to them with a for loop. I don't think you need a two dimensional array, however.

public static void DisplayInventory() throws FileNotFoundException
{
String[] sArray = new String[15]; //I'm assuming there are 15 values being added
String[][] sArray2 = new String[10][10]; //Not sure how many are being added
//Remember, make sure you don't use less space than you need.

    try
    {
        Scanner autoInventory = new Scanner(new File("records.txt"));

        for (int Num = 0; Num < 15; Num++)
        {
            String autoRecords = autoInventory.nextLine();
            autoRecords = autoRecords.replace(';', ' ');
            sArray[Num] = autoRecords;
            System.out.println(sArray[Num]);
        }

I think that should suffice, since I don't believe you need a two dimensional array; it seems like what you're trying to do can be managed with a regular array. That being said, I'm still not entirely aware on what you're trying to do, so if you really need to use a two dimensional array, just add another for loop, and when working with the array, you will probably (not necessarily) need to keep the value of the first for loop within the first bracket, and the nested in the second - like this:

sArray2[Num][Num2];

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