简体   繁体   English

将字符串追加到2d Array Java中

[英]Appending a string into 2d Array Java

I have a string containing the following: 我有一个包含以下内容的字符串:

String text = "abcdefghijkl"

I want to put it in a 2d array so there will be 4 rows of 3 我想将它放在2d数组中,所以会有4行,每行3

this is currently what I have, its not working correctly though: 这是我目前所拥有的,尽管它不能正常工作:

char boxChar[][] = new char[4][3];
        int j,i;

        for (i = 0; i<4; i++)
        {
            for (j=0; j<3; j++)
            {            

                boxChar[i][j] = text.charAt((i+1)*(j));

            }

        }

        return boxChar[row][col];

It looks like you got the indexes mixed up. 看来您混合了索引。 I added some print statements to your original code with a modification to get the right char in your charAt instruction. 我在原始代码中添加了一些打印语句,并进行了修改,以便在charAt指令中获得正确的char。

    String text = "abcdefghijkl";

    char boxChar[][] = new char[4][3];
    int j,i;

    for (i = 0; i<4; i++)
    {
        for (j=0; j<3; j++)
        {            

            boxChar[i][j] = text.charAt(i*3+j);
            System.out.print(boxChar[i][j]);
        }
        System.out.println();

    }

Sometimes it can be helpful to jot it down on a piece of paper if it's not lining up how you expected. 有时,如果没有按照您的期望排列,将其记在一张纸上会很有帮助。

With your input string, the positions on a 1d array are 使用您的输入字符串,一维数组上的位置为

a    b    c    d    e    f    g    h    i    j    k    l
0    1    2    3    4    5    6    7    8    9   10   11

As you loop through to get the box array (matrix), your outer loop indicates that you want four rows and three columns, in other words 当您循环获取框数组(矩阵)时,外部循环表明您需要四行三列,换句话说

a    b    c
d    e    f
g    h    i
j    k    l

so for the first element, a , its position is (0,0) , b is at (0,1) and so on. 因此对于第一个元素a ,其位置为(0,0)b处于(0,1) ,依此类推。 Your charAt(position) has to map the 2d positions to their corresponding 1d positions. 您的charAt(position)必须将2d位置映射到其对应的1d位置。

Just the wrong indexing, otherwise you're good: 只是错误的索引编制,否则您就很好:

String text = "abcdefghijkl";
int rows = 4;
int cols = 3;
char boxChar[][] = new char[rows][cols];

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {            
        boxChar[i][j] = text.charAt((i * cols) + j);
    }
}

//return boxChar[row][col];

System.out.println(boxChar[0]);
System.out.println(boxChar[1]);
System.out.println(boxChar[2]);
System.out.println(boxChar[3]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM