[英]Moving array elements left and right
因此,作為我要創建的Vector
類的一部分,我還希望用戶能夠根據指定的內容將數組中的元素移位'n'
個位置。 如果用戶輸入的數字大於數組的大小,則元素將繼續移回起點並移動。 一個例子是:
1 2 3 4 (shifted 1) => 4 1 2 3
1 2 3 4 (shifted 4) => 1 2 3 4
1 2 3 4 (shifted 5) => 4 1 2 3
到目前為止,我沒有多少代碼,除了:
public Vector shifted(int amount) {
Vector vectorShifted = new Vector(length);
for (int i = 0; i < length; i++);
vectorShifted.elements[i] = this.elements[i + amount]
}
return vectorShifted;
}
但是,當我運行該程序並輸入大於length
的數字時,將顯示錯誤。 有沒有一種方法可以修改此代碼,因為可以輸入任何數字(正數或負數)並在數值之間移動?
就像lazary2所說的那樣,您可以使用模運算符%
更改: vectorShifted.elements[i] = this.elements[i + amount]
到vectorShifted.elements[i] = this.elements[(i + amount) % length]
如果要使用數組:
Integer[] array = {0,1,2,3,4}; Collections.rotate(Arrays.asList(array), 3); System.out.println(Arrays.toString(array)); //[2, 3, 4, 0, 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.