如何创建一个多维数组以从.txt文件中获取输入并将字符串和数字分开存储

时间:2015-11-01 14:34:26

标签: java file text multidimensional-array input

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"
 }
}

如何制作以下代码以将字符串拆分为多个并将其存储在多维数组中?例如:

文本:

123 abc 456

789 def 101 112

阵列

[123] [abc] [456]

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

文本中的数字在存储到数组之前转换为数字。我相信我必须使用Integer parsed.Int()。不确定如何实现它

1 个答案:

答案 0 :(得分:0)

通过以下更正,您最终会得到包含正确分割字符串的entries数组。

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

}
}

此时,您的条目数组将如下所示:

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

因此,您现在可以编写自己的循环并根据需要进行处理。