我试图从2d char数组中打印字符但是我不断回来一个字符串而不是每个字母。例如命令行中的参数是
“ - 加密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]);
答案 0 :(得分: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
2D字符数组上清除分配和打印逻辑。
根据您对评论的回复,您需要将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]);
}
}
答案 1 :(得分: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]
的事情。