将int数组的内容右移到num

时间:2015-11-29 05:40:25

标签: java arrays

我试过了:

trigger-build-and-sync

但发现它并没有交换价值。然后我从这里接受了帮助 {{3}}

watchman -j <<-EOT
["trigger", "/path/to/root", {
   "name": "build-and-sync",
   "expression": ["suffix", "py"],
   "command": "/path/to/trigger-build-and-sync",
   "append_files": false,
   "stdin": "NAME_PER_LINE"
}]
EOT

它使数组超出异常范围。

  1. 哪里错了?
  2. public static void main(String[] args) { int array [] = {2, 5, 1, 4, 7, 9, 0}; for (int i = 0; i < array.length-2; i++) { swapNum(array[i], array[i+2]); System.out.println(Arrays.toString(array)); } System.out.println(Arrays.toString(array)); } public static void swapNum(int a, int b){ int tmp = a; a = b; b = tmp; } 变量的作用。如果public void anotherTry() { int nums [] = {4, 5, 2, 1, 6, 8}; for (int i = 0, start = 0; i < nums.length; i++) { if (i == 0) start = nums[i]; if (i == (nums.length - 1)) { nums[i] = start; break; } nums[i+2] = nums[i]; System.out.println(Arrays.toString(nums)); } System.out.println(Arrays.toString(nums)); } 始终等于start

1 个答案:

答案 0 :(得分:1)

您无法在Java中交换类似的值。但是,由于您正在使用数组并希望交换数组中的值,因此可以重写swap方法以使用索引:

public static void main(String[] args) {
    int array [] = {2, 5, 1, 4, 7, 9, 0};

    for (int i = 0; i < array.length-2; i++) {
        swapNum(array, i, i+2);
    System.out.println(Arrays.toString(array));
    }

    System.out.println(Arrays.toString(array));
}
public static void swapNum(int[] values, int i, int j){

    int tmp = values[i];
    values[i] = values[j];
    values[j] = tmp;

}