对于我的一个方法,它的作用是切换数组的第一个和最后一个元素。当我将数组内置到方法中时,它工作得很好。但后来我决定让它从main读取一个数组,现在它无法正常工作。它每次都会替换不同的数字,或者有时不会替换任何内容,只是复制数组。示例:20432 20432和44413 44431和42203
public static void main(String[] args) {
int[] array = new int[5];
int length = array.length;
for (int i = 0; i < length; i++) {
array[i] = (int)(Math.random () * 5);
System.out.print(array[i]);
}
System.out.println("");
flipFirstAndLast(array);
replaceEvenWithZero(array);// TODO code application logic here
}
public static void flipFirstAndLast(int[] array){
int i = array[0];
int j = array[array.length - 1];
int hold = array[i];
array[i] = array[j] ;
array[j] = hold;
for (int k = 0; k < 5; k++) {
System.out.print(array[k]);
}
System.out.println("");
}
public static void flipFirstAndLast(int[] array){
int i = array[0];
int j = array[array.length - 1];
int hold = array[i];
array[i] = array[j] ;
array[j] = hold;
for (int k = 0; k < 5; k++) {
System.out.print(array[k]);
}
只需复制此代码,您将得到您的答案,我尝试了它,它的工作
public static void flipFirstAndLast(int[] array){
for( int i=0;i<array.length;i++)
System.out.println( " array in mathod : " +array[i]);
System.out.println("");
int i = array[0];
int j = array[array.length-1];
array[0]=j;
array[array.length-1]= i;
System.out.println("after swap");
for (int k = 0; k < 5; k++) {
System.out.print(array[k]);
}
System.out.println("");
}
或者你也可以这样做
public static void flipFirstAndLast(int[] array){
for( int i=0;i<array.length;i++)
System.out.println( " array in mathod : " +array[i]);
System.out.println("");
// int i = array[0]; //remove this line
// int j = array[array.length-1]; // remove this line
int hold =0;
hold = array[0];
array[0] = array[array.length-1] ;
array[array.length-1] = hold;
System.out.println("after swap");
for (int k = 0; k < 5; k++) {
System.out.print(array[k]);
}
System.out.println("");
}