gpt4 book ai didi

java - 分配新数组时出现 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 12:20:10 24 4
gpt4 key购买 nike

我正在尝试将一个数组排序为另外两个必须具有精确长度的数组。运行此命令时,为什么我会收到错误 Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 2 at Tal.main(Tal.java:39) ?我知道有更好的方法来解决这个任务,但我不被允许这样做。我必须这样做。

public static void main(String[] args) 
{
Scanner in = new Scanner(System.in);

System.out.print("How many random numbers from 0 to 999? ");
int amount = in.nextInt();

int lowerCounter = 0;
int higherCounter = 0;
int[] numbers = new int[amount];
System.out.print("Here is the random numbers: ");
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = (int) Math.floor(Math.random()*1000);
System.out.print(numbers[i] + " ");

if (numbers[i] <= 499) {
lowerCounter++;
}
else {
higherCounter++;
}
}
System.out.println("");


int[] numbersLow = new int[lowerCounter];
int[] numbersHigh = new int[higherCounter];
for(int i = 0; i < numbers.length; i++)
{
if (numbers[i] <= 499)
{
numbersLow[i] = numbers[i];
} else {
numbersHigh[i] = numbers[i];
}
}

System.out.print("These "+ lowerCounter +" numbers are from 0 to 499: ");
for(int i = 0; i < numbersLow.length; i++)
{
System.out.print(numbersLow[i] + " ");
}

System.out.println("");

System.out.print("These "+ higherCounter +" numbers are from 500 to 999: ");
for(int i = 0; i < numbersHigh.length; i++)
{
System.out.print(numbersHigh[i] + " ");
}

}

最佳答案

您的循环变量不正确。您应该修复您的代码,以便为两个数组提供 2 个不同的计数器,并让一个计数器循环遍历主计数器。

lowerCounter=higherCounter=0;
for(int i = 0; i < numbers.length; i++) {
if (numbers[i] <= 499) {
numbersLow[lowerCounter++] = numbers[i];
} else {
numbersHigh[higherCounter++] = numbers[i];
}
}

关于java - 分配新数组时出现 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723448/

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