简体   繁体   English

左右移动数组元素

[英]Moving array elements left and right

So as part of the Vector class I'm trying to create, I also want the ability for the user to be able to shift the elements in the array an 'n' number of places depending on what is specified. 因此,作为我要创建的Vector类的一部分,我还希望用户能够根据指定的内容将数组中的元素移位'n'个位置。 If the user inputs a number that is larger than the array size, then the elements continue shifting back to the start and moving. 如果用户输入的数字大于数组的大小,则元素将继续移回起点并移动。 An example would be: 一个例子是:

 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

I don't have much code so far except: 到目前为止,我没有多少代码,除了:

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;
}

However, when I run this program and a number greater than length is entered, an error is displayed. 但是,当我运行该程序并输入大于length的数字时,将显示错误。 Is there a way of modifying this code in that any number, positive or negative can be inputted and shift the values across? 有没有一种方法可以修改此代码,因为可以输入任何数字(正数或负数)并在数值之间移动?

Just like lazary2 said, you can use the modulo operator % 就像lazary2所说的那样,您可以使用模运算符%

Change: vectorShifted.elements[i] = this.elements[i + amount] 更改: vectorShifted.elements[i] = this.elements[i + amount]

to vectorShifted.elements[i] = this.elements[(i + amount) % length] vectorShifted.elements[i] = this.elements[(i + amount) % length]

If you want to use Array: 如果要使用数组:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM