Java:从输入文件填充二维数组

时间:2012-01-31 02:55:32

标签: java

基本上,我需要扫描它(来自输入.txt文件):

oooooooo
#S#ooooo
oo#oo##o
ooo#ooo#
oo#oo$oo
o######o
oooooooo

进入二维数组。这是我到目前为止所做的:

public static void main(String[] args) throws IOException
{
    Scanner scan = new Scanner(new File("inputFile.txt"));
    numRows = scan.nextInt();
    numColumns = scan.nextInt();
    mazeArray = new char[numRows][numColumns];


    for(int row = 0; row < numRows; row++)
    {
        strings = scan.next();

        for(int column = 0; column < numColumns; column++)
        {
            mazeArray[row][column] = strings.charAt(row);
            System.out.print(mazeArray[row][column]);
        }
        System.out.print("\n");
    }
}

输出完全错误:

oooooooo
SSSSSSSS
########
########
oooooooo
########
oooooooo

2 个答案:

答案 0 :(得分:5)

// Change row -> column

mazeArray[row][column] = strings.charAt(column);

答案 1 :(得分:0)

System.out.println()将始终打印一个新行。相反,您应该使用System.out.print()并在每行后打印换行符“\ n”。

试试这个:

for(int row = 0; row < numRows; row++)
{
    strings = scan.next();
    for(int column = 0; column < numColumns; column++)
    {
        mazeArray[row][column] = strings.charAt(row);
        System.out.print(mazeArray[row][column]);
    }
    System.out.print("\n");
}