交换数组中的第一个和最后一个值(JAVA)

时间:2016-11-12 20:57:53

标签: java arrays

我相信代码有效但测试人员代码不是,我不知道为什么。我试图交换数组中的第一个和最后一个值。

public class ArrayMethods {

 private int[] values;
 public ArrayMethods(int[] initialValues) {
    values = initialValues;
  }
 public void swapFirstAndLast() {
    int lastvalplace = values.length;
    int firstval = values[0];
    values[0] = values[lastvalplace];
    values[lastvalplace] = firstval;
 }

 public static void main(String[] args) {
     ArrayMethods initialValues = new ArrayMethods(int[] 50, 32, 4, 9, 2);
     swapFirstAndLast = new swapFirstAndLast(values);
 }

}

1 个答案:

答案 0 :(得分:1)

嗯,这是基本的swap + 0-indexed数组的情况。

int lastElement = values[values.length-1];
values[values.length-1] = values[0];
values[0] = lastElement;

您的代码生成ArrayOutOfBoundsException,它会给出一个堆栈跟踪,它会打印出问题所在的行以及索引太大的信息。它还为您提供索引。

你有类似的东西:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at ArrayMethods.swapFirstAndLast(ArrayMethods.java:10)

请记住,Java中数组的最后一个元素是array[array.length-1]

还有一个问题。你的主要:

ArrayMethods initialValues = new ArrayMethods(new int[]{50, 32, 4, 9, 2});
initialValues.swapFirstAndLast();
相关问题