所以我必须创建一个Java程序,用户在其中说明要输入多少个值,在数组中输入多个值,打印数组。然后我必须反转数组中的元素(不反转打印或创建一个新数组),然后再次打印这些值。这是我的以下代码:
package reversearray;
import java.util.*;
public class Swap_main {
/**
* Taylor Marino
*/
public static void main(String[] args) {
int arraysize = 0, junk, junk2;
Scanner reader = new Scanner(System.in);
System.out.println("How many values are you going to enter?");
arraysize = reader.nextInt();
int[] array = new int[arraysize];
System.out.println("You will now be asked to enter your values, one at a time");
for(int counter = 0; counter < arraysize; counter++){
System.out.println("Enter next value");
array[counter] = reader.nextInt();
}
System.out.println("The values you entered are: ");
for(int counter2 = 0; counter2 < arraysize; counter2++)
System.out.print(array[counter2] + ", ");
for(int counter3 = 0, counter4 = arraysize; counter3 != counter4; counter3++, counter4--){
junk = array[counter3];
junk2 = array[counter4];
array[counter4] = junk;
array[counter3] = junk2;
}
System.out.println("The values you entered are (in reverse order): ");
for(int counter5 = 0; counter5 < arraysize; counter5++)
System.out.print(array[counter5] + ", ");
}
}
但是我在这个循环中收到错误:
for(int counter3 = 0, counter4 = arraysize; counter3 != counter4; counter3++, counter4--){
junk = array[counter3];
junk2 = array[counter4];
array[counter4] = junk;
array[counter3] = junk2;
}
我不知道这里有什么问题,但它说array[counter4] = junk;
出错了
我做错了什么?
答案 0 :(得分:3)
由于数组从0索引到长度为1,因此会给出一个ArrayOutOfBoundsException。从counter4 = arraysize-1开始。
编辑:另外,你应该改变
counter3 != counter4
到
counter3 < counter4
因为在奇数长度的数组上,第一个条件永远不会给你真实。
答案 1 :(得分:0)
更改
for(int counter3 = 0, counter4 = arraysize
到
for(int counter3 = 0, counter4 = arraysize-1
答案 2 :(得分:0)
尝试
for(int counter3 = 0, counter4 = arraysize -1 ; counter3 < counter4 ; counter3++, counter4--){
有效。例外消失了。
答案 3 :(得分:0)
可能稍微简洁一些,只使用一个循环变量
int maxIndex = array.length-1; // Zero based
int midIndex = (maxIndex/2); // only swap half, otherwise will swap back to original
for(int counter3 = 0; counter3 <= midIndex; counter3++){
junk = array[counter3];
array[counter3] = array[maxIndex-counter3];
array[maxIndex-counter3] = junk;
}