按字符阅读文本文件字符转换为2D的char [] []数组 [英] Reading text file character by character into a 2d char[][] array

查看:137
本文介绍了按字符阅读文本文件字符转换为2D的char [] []数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在叫test.txt的文本文件阅读。文本文件的第一行是两个整数。这些整数告诉你二维字符数组的行和列。该文件的其余部分包含的字符。该文件看起来有点像:对于某些信息4 4档,除了垂直彼此不是水平之上。然后,我必须阅读每个文件的内容,其余的到2D的char [] []使用嵌套的for循环数组。我不应该复制从一个阵列到另一个。这是code我有这么远。我有麻烦读一行每个字符线到我的二维字符数组。帮助在这已经工作了几个小时。

I have to read in a text file called test.txt. the first line of the text file are two integers. these integers tell you the rows and columns of the 2D char array. The rest of the file contains characters. the file looks a bit like: 4 4 FILE WITH SOME INFO except vertically on top of one another not horizontally. I must then read each of the rest of the contents of the file into the 2D char[][] array using nested for loops. I am not supposed to copy from one array to another. This is the code I have so far. I'm having trouble reading each character line by line into my 2D char array. Help been working at this for hours.

    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();


}

}

推荐答案

如果我理解正确的是 - 文件格式是一样的东西。

If I have understood it correctly - file format is something like

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();
    }

以上code是你初始化字符数组。为了打印,你可以这样做

Above code is for initialization of you char array. In order to print the same you can do something like

Arrays.deepToString(array);

这篇关于按字符阅读文本文件字符转换为2D的char [] []数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆