简体   繁体   中英

How to create a multidimensional Array to take input from .txt file and store the strings and the numbers separate

public class ArrayDirectory {
public static void main(String args[]) throws FileNotFoundException {
    String file = ("lab4b2.txt");
    Scanner scan = new Scanner(new FileReader(file));
    // initialises the scanner to read the file file

    String[][] entries = new String[100][3];
    // creates a 2d array with 100 rows and 3 columns.

    int i = 0;
    while(scan.hasNextLine()){
        entries[i] = scan.nextLine().split("\t");
        i++;
    }
    //loops through the file and splits on a tab

    for (int row = 0; row < entries.length; row++) {
        for (int col = 0; col < entries[0].length; col++) {
            if(entries[row][col] != null){
                System.out.print(entries[row][col] + " " );
            }
        }
        if(entries[row][0] != null){
             System.out.print("\n");
        }
    }
    //prints the contents of the array that are not "null"
 }
}

How do I make the following code to split the string into pieces and store them in the multidimentional array? For example:

Text:

123 abc 456

789 def 101 112

array

[123] [abc] [456]

[789] [def] [101] [112]

The numbers from the text being converted to numbers before stored in the array. I believe I have to use Integer parsed.Int(). not sure how to implement it

With the following corrections, you would end up with the entries array with the splitted strings correctly.

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

String file = ("C:\\array.txt");
Scanner scan = new Scanner(new FileReader(file));
// initialises the scanner to read the file file

String[][] entries = new String[100][3];
// creates a 2d array with 100 rows and 3 columns.

int i = 0;
while(scan.hasNextLine())
{
    String [] splittedEntries = new String[3];
    splittedEntries = scan.nextLine().split(" ");

    for( int inx = 0; inx < splittedEntries.length; ++inx )
    {
        entries[i][inx] = splittedEntries[inx];
    }
    i++;

}
}

At this moment, your entries array would look like this:

entries[0] = { 123, abc, 456 };
entries[1] = { 789, def, 101 };

So, you can write your own loops now and process as required.

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