在 int 数组 java 中重新排列 int 值



所以我必须制作一个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;有错误我做错了什么?

这将为您提供一个 ArrayOutOfBoundsException,因为数组的索引从 0 到 length-1。从计数器 4 = 数组大小-1 开始。

编辑:另外,您应该更改

counter3 != counter4

counter3 < counter4

因为在奇数长度的数组上,第一个条件永远不会给你 true。

更改

for(int counter3 = 0, counter4 = arraysize

for(int counter3 = 0, counter4 = arraysize-1

试试

for(int counter3 = 0, counter4 = arraysize -1 ; counter3 < counter4 ; counter3++, counter4--){

它有效。例外消失了。

可以稍微简洁一些,只使用一个循环变量

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

最新更新