我正在尝试将一个数组排序到另外两个必须精确长度的数组。为什么运行此错误时会收到错误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] + " ");
}
}
答案 0 :(得分:1)
您的循环变量不正确。你应该修改你的代码,以便为两个数组和一个计数器提供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];
}
}
答案 1 :(得分:0)
最好的方法是使用Java 8:
int[] lowerThan500 = Arrays.stream(numbers).filter(i -> i < 500).toArray();
代码少,错误少。
或者:
long nbLessThan500 = Arrays.stream(numbers).filter(i -> i < 500).count();