逐个字符地将文本文件读入2d char [] []数组

时间:2014-10-25 21:44:02

标签: java arrays multidimensional-array

我必须在一个名为test.txt的文本文件中读取。文本文件的第一行是两个整数。这些整数告诉您2D char数组的行和列。文件的其余部分包含字符。该文件看起来有点像:4 4 FILE WITH SOME INFO除了垂直在另一个上面而不是水平。然后,我必须使用嵌套的for循环将文件的其余内容读入2D char [] []数组。我不应该从一个数组复制到另一个数组。这是我到目前为止的代码。我无法逐行读取每个字符到我的2D字符数组中。帮助我们工作了几个小时。

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



    File inFile = new File("test.txt");                                 
    Scanner scanner = new Scanner(inFile);     
    String[] size = scanner.nextLine().split("\\s");         

    char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];

    for(int i=0; i < 4; i++) {
        array[i] = scanner.nextLine().toCharArray();
    }

    for(int k = 0; k < array.length; k++){
        for(int s = 0; s < array[k].length; s++){
            System.out.print(array[k][s] + " ");
        }
        System.out.println();
    }

     scanner.close();


}

}

2 个答案:

答案 0 :(得分:1)

如果我理解正确 - 文件格式就像

4 4
FILE
WITH
SOME
INFO

修改如下

    Scanner scanner = new Scanner(inFile);     
    String[] size = scanner.nextLine().split("\\s");         

    char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];

    for(int i=0; i < rows; i++) {
        array[i] = scanner.nextLine().toCharArray();
    }

上面的代码用于初始化char数组。要打印相同的内容,您可以执行类似

的操作
Arrays.deepToString(array);

答案 1 :(得分:0)

复制Tirath的文件格式:

4 4 文件 WITH 一些 INFO

我会将它传递给二维数组,如下所示:

public static void main(String[] args){

    char[][] receptor = null;   //receptor 2d array
    char[] lineArray = null;    //receptor array for a line

    FileReader fr = null;
    BufferedReader br = null;
    String line = " ";

    try{
    fr = new FileReader("test.txt");
    br = new BufferedReader(fr);

        line = br.readLine();//initializes line reading the first line with the index
        int i = (int) (line.toCharArray()[0]-48); //we convert line to a char array and get the fist index (i) //48 = '0' at ASCII
        int j = (int)(line.toCharArray()[1]-48); // ... get the second index(j)

        receptor = new char[i][j];  //we can create our 2d receptor array using both index

        for(i=0; i<receptor.length;i++){
                line = br.readLine(); //1 line = 1 row
                lineArray = line.toCharArray(); //pass line (String) to char array
            for(j=0; j<receptor[0].length; j++){ //notice that we loop using the length of i=0
                receptor[i][j]=lineArray[j];    //we initialize our 2d array after reading each line
            }
        }

    }catch(IOException e){
        System.out.println("I/O error");
    }finally{
        try {
            if(fr !=null){
            br.close();
            fr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } //end try-catch-finally
}