gpt4 book ai didi

java - 重新排列 int 数组中的 int 值 java

转载 作者:行者123 更新时间:2023-12-02 00:02:03 25 4
gpt4 key购买 nike

所以我必须编写一个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。从 counter4 = arraysize-1 开始。

编辑:另外,你应该改变

counter3 != counter4

counter3 < counter4

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

关于java - 重新排列 int 数组中的 int 值 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14652607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com