2016-11-12 74 views
1

我相信代码可以正常工作,但测试人员代码不是,我不知道为什么。我试图交换数组中的第一个和最后一个值。交换数组中的第一个和最后一个值(JAVA)

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

} 
+0

*“我相信代码有效”*您应该测试它,并确保不只是假设。另外,“测试代码”会发生什么? – UnholySheep

+1

你是什么意思“不起作用”?我猜它甚至没有编译,是吗? – Gernot

+0

数组中的最后一个元素是'array [array.length - 1]'(而不是你的代码中的'array [array.length]') –

回答

1

嗯,这是基本的swap + 0索引数组的情况。

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(); 
相关问题