0

我试图从 2d 字符数组中打印字符,但是我不断返回一个字符串而不是每个字母。例如命令行中的参数是

“-加密 abcdefghij”

    String command = args[0]; 
    String Text = args[1]; //letters to be 

    char letters [] = Text.toCharArray(); 
    int m = Text.length(); //number of letters to be decrypted/encrypted


    String command = args[0]; 
    String Text = args[1]; //leters to be 

    char letters [] = Text.toCharArray(); 
    int m = Text.length(); //number of letters to be decrypted/encrypted


    if (command.equals("-encrypt")) {

        //if statement was here before for perfect square numbers

        else if     ( m / (int) Math.sqrt(m) != Math.sqrt(m) ) { //non perfect square digits

        int RootM = (int) Math.pow((Math.sqrt(m))+1,2); //overall size of 2d array (depth*width)
        int RootN1 = (int) Math.sqrt(RootM); //length of rows & columns

        char [][] box = new char [RootN1][RootN1]; //define dimensions of 2d array

            for (int i=0; i<RootN1; i++) {
                for (int j=0; j<RootN1; j++) {
                    box[i][j]=letters[2*i+j];
                }
            }

            for (int i=0; i<RootN1; i++) {
                for (int j=0; j<RootN1; j++) {  

            System.out.print(box[j][i]); 
4

2 回答 2

0
 for (int i=0; i<RootM; i++) {
    for (int j=0; j<RootM; j++) {
      box [i] = letters;
      box [j] = letters;
      System.out.print(box[i]); //displays encrypted text
    }
 }

是有问题的。您放入box[i] = letters内部循环,因此它将被执行RootM*RootM多次,这与print语句相同。您可能需要清除box二维字符数组上的分配和打印逻辑。

根据您对评论的回复,您需要将 abcd 放入2*2矩阵中,第一行包含ab,第二行包含cd。您可以找到索引映射如下:

index in 1D array:
    0    1    2  3

index in 2D array:

  (0,0) (0,1) (1,0) (1,1)

所以映射是:

box[i][j] = letters[2*i+j];

现在假设您有一个 4*4 矩阵:

index in 1D array:
0  1  2  3  4 5  6  7  8  9  10  11  12  13  14  15

index in 2D array:
(0,0),(0,1),(0,2),(0,3),(1,0),(1,2) ....

您将需要映射

box[i][j] = letters[4*i+j];

简而言之,如果行数为 N,则需要

box[i][j] = letters[N*i + j];

您的循环应如下所示:

for (int i=0; i<RootM; i++) {
  for (int j=0; j<RootM; j++) {
    box [i][j] = letters[2*i+j];
  }
}

//you can now print column by column
for (int i=0; i<RootM; i++) {
  for (int j=0; j<RootM; j++) {
     System.out.print(box [j][i]);
  }
}
于 2013-04-13T13:03:02.370 回答
0

您在级联 for 循环中执行的操作如下:

box[0] = "abcd";
box[0] = "abcd";
box[0] = "abcd";
box[1] = "abcd";
box[1] = "abcd";
box[0] = "abcd";
...

我不完全知道您是如何尝试填充该二维数组的,但我想您将不得不做类似于box[i][j] = letters[2*i+j].

于 2013-04-13T13:15:37.830 回答