gpt4 book ai didi

java - for循环内的System.arraycopy不是切换矩阵行吗?

转载 作者:行者123 更新时间:2023-11-30 03:30:21 25 4
gpt4 key购买 nike

System.out.println("Before decryption:");
System.out.println(Arrays.deepToString(output));
int top, bottom;
bottom = this.size-1;
for(top = 0; top<bottom; top++,bottom--){
char[] topMatrix = output[top];
char[] bottomMatrix = output[bottom];
System.out.println(top+" "+bottom);
System.arraycopy(topMatrix, 0, output[bottom], 0, size);
System.arraycopy(bottomMatrix, 0, output[top], 0, size);
}
System.out.println("After Decryption: ");
System.out.println(Arrays.deepToString(output));
}

上面是我用来切换第一行和最后一行的代码,然后是第二行和第二行到最后一行,依此类推,直到用完要在二维数组中切换的行。

这是输出:

Input: abcdefghi
Before decryption:
[[a, b, c], [d, e, f], [g, h, i]]
0 2
After Decryption:
[[a, b, c], [d, e, f], [a, b, c]]

所以这里似乎发生的是 arraycopy 确实将第一行复制到最后一行,但不知何故,bottomMatrix 变量似乎更新为 (abc) 而不是其原始 (ghi)。

什么给了?看起来它执行了第一个 arraycopy,然后退出循环并返回,而不是执行循环中的所有语句。

最佳答案

您正在将代码复制到同一个数组,因此当您的顶部写入底部时,它会覆盖底部,然后相同的内容会写入顶部。您通过 ghi 复制 abc,然后尝试将 abc 复制到 abc。

您应该使用不同的数组进行输入和输出以避免此问题。

System.out.println("Before decryption:");
System.out.println(Arrays.deepToString(output));
int top, bottom;
bottom = this.size-1;
char[][] copy = new char[size][size];
for(top = 0; top<=bottom; top++,bottom--){
char[] topMatrix = output[top];
char[] bottomMatrix = output[bottom];
System.out.println(top+" "+bottom);
System.arraycopy(topMatrix, 0, copy[bottom], 0, size);
System.arraycopy(bottomMatrix, 0, copy[top], 0, size);
}
System.out.println("After Decryption: ");
System.out.println(Arrays.deepToString(copy));

另请注意,我已更改为 <= 而不是 <,因为您正在写入一个新数组,因此在奇数大小的数组的情况下,如果您仅使用 <,它不会复制中心行。对于偶数大小的数组,相同的条件将起作用,因为处理完一半后顶部>底部。

关于java - for循环内的System.arraycopy不是切换矩阵行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29188287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com