gpt4 book ai didi

java - 数组向右移动,但索引 [0] 消失了

转载 作者:行者123 更新时间:2023-11-29 04:35:45 26 4
gpt4 key购买 nike

我正在向右移动一个数组,但是当我这样做时我丢失了原始数组 [0]。

int innerLastIndex = innerRotorClockWise.length - 1;

String innerOldLast = innerRotorClockWise[innerLastIndex];

for (int i = innerLastIndex; i != 0; i--) {

//place a holder for first and last.

innerRotorClockWise[i] = innerRotorClockWise[i-1];


innerRotorClockWise[0] = innerOldLast;

输出:

原创

[#, G, N, U, A, H]

平移 1

[H, H, G, N, U, A] 

移动 2

[A, A, H, G, N, U]

我看过其他人,他们似乎没有帮助解决这个问题。我是否也必须为我的第一个元素创建一个占位符?

最佳答案

您似乎在循环中放置了以下语句:

innerRotorClockWise[0] = innerOldLast;

这会导致第 0 个元素在第一次迭代中被替换。在第一个语句本身之后关闭循环:

for (int i = innerLastIndex; i != 0; i--) {

innerRotorClockWise[i] = innerRotorClockWise[i-1];

}
innerRotorClockWise[0] = innerOldLast;

以下代码适用于我:

    String[] innerRotorClockWise = new String[]{"#", "G", "N", "U", "A", "H"};
int innerLastIndex = innerRotorClockWise.length - 1;

String innerOldLast = innerRotorClockWise[innerLastIndex];

for (int i = innerLastIndex; i != 0; i--) {


innerRotorClockWise[i] = innerRotorClockWise[i - 1];

}
innerRotorClockWise[0] = innerOldLast;
System.out.println(Arrays.toString(innerRotorClockWise));

关于java - 数组向右移动,但索引 [0] 消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41627999/

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