0

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.

6
  • 3
    Can you show us the structure of your input records.txt file? Commented Jun 24, 2015 at 0:52
  • Yes, it is a 14 row by 7 column text file that has different types of food, their attributes, and pricing. Commented Jun 24, 2015 at 0:59
  • 1
    @Paul include the actual contents of the text file as part of your question.. Commented Jun 24, 2015 at 1:04
  • So what you going to store in that array, can you give an example how the array should look? Commented Jun 24, 2015 at 1:05
  • @Paul edit your question and include about 2 lines of your text file Commented Jun 24, 2015 at 1:07

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

8 Comments

Hi trooper, so is all of this in the main method or is it in the method that displays the array?
yes, it can all be in the main method. I intentionally broke it up hoping you would learn more that way, rather than just providing a canned answer. I hope this still helps.
you can of course declare the array as a member of your class, have a separate function that reads your file and populates it, and a separate function that prints it to the screen, and then your main method would create an instance of your class and call the appropriate methods - that is all beyond the scope of the question though.
Thank you for your help. I am still confused on how to print it, can you just elaborate on that further?
Added some code that prints. It is just iterating over the array again, and to make things pretty, putting the , and newlines back into the output.
|
0

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

5 Comments

This answer also works! One thing, the first line of the text file has a 14 and 7 on it representing the number of rows and columns of the document, how would I get rid of that when printed?
Glad I could help. As for how to get rid of that, I'd suggest either directly editing it in the text file, or use some string methods ( docs.oracle.com/javase/7/docs/api/java/lang/String.html ). I'd probably do something along the liens of checking if the numbers are there (.contains()) and then replace it using the replace() method. From there, depending on the string itself - and if you care about spaces here and there - I'd suggest using the trim() method. Let me know if that's what you were looking for.
Yes, I can't edit the text file, but I can use a string method. Also, how exactly would I add the other for loop for the two dimensional array? And would I delete the first sArray?
Yeah, if you're doing a 2D array, you don't need the first one. As for how to add the for loop, just nest it, which is placing the second for loop inside the first one.
how would the 2d array be different if you didn't know how many values were going to be in it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.