我想將一個數組排序到兩個其他數組必須是精確的長度。爲什麼在運行時出現錯誤Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Tal.main(Tal.java:39)
?我知道有更好的方法來解決這個任務,但我不被允許。我必須這樣做。分配新陣列時ArrayIndexOutOfBoundsException
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] + " ");
}
}
對不起,你怎麼能指望我們知道'Tal.java:39'是從您發佈的代碼? – 2014-11-03 21:25:27
'numbersLow [i]'可以根據定義拋出一個異常,因爲'i
njzk2
2014-11-03 21:26:52
我可以確實這樣做,但是我的新陣列不會被完全填滿。 – superior 2014-11-03 21:27:29