2014-10-05 131 views
-2

我想創建一個程序,根據用戶的輸入創建一個數組,用戶還可以輸入最大和最小數字。下面的代碼:爲什麼我的代碼導致ArrayIndexOutOfBoundsException?

//Ask the user to enter the length of the array 
System.out.println("Please enter the length of the array: "); 
int arraylength = input.nextInt(); 

//Ask the user to enter a max value 
System.out.println("Please enter the max value: "); 
int max = input.nextInt(); 

//Ask the user to input the min value 
System.out.println("Please enter the min value: "); 
int min = input.nextInt(); 

//Initialize the array based on the user's input 
double [] userArray = new double[arraylength]; 


int range = (int)(Math.random() * max) + min; 

/** 
*The program comes up with random numbers based on the length 
*entered by the user. The numbers are limited to being between 
*0.0 and 100.0 
*/ 
for (int i = 0; i < userArray.length; i++) { 
    //Give the array the value of the range 
    userArray[arraylength] = range; 
    //Output variables 
    System.out.println(userArray[arraylength]); 
} 

這個問題似乎是與陣列的輸入的長度,在這一行:

userArray[arraylength] = range; 

我一直在尋找一個答案,但沒有拿出任何東西,任何幫助將非常感激。

+2

您認爲在'userArray [arraylength]'中發生了什麼? ''['''中可以使用什麼值,'arraylength'中存儲了什麼值? – Pshemo 2014-10-05 18:43:36

+1

它告訴你,數組索引大於可以在該數組上使用的最大索引。如果你創建一個大小爲arrayLength的數組,那麼根據定義,arrayLength將會是一個太大而不能作爲該數組的索引的數組。 (我懷疑你打算說'userArray [i]'而不是'userArray [arrayLength]'。) – 2014-10-05 18:44:44

回答

2

你是對有問題的線路。這是

userArray[arraylength] = range; 

要明白髮生了什麼,你需要知道

  • 數組的長度爲arraylength
  • 數組元素編號/索引值從0到arraylength-1

userArray[arraylength]這樣的調用會導致java.lang.ArrayIndexOutOfBoundsException,因爲您嘗試訪問索引6處的元素,而highes t允許值爲5.

1

該代碼塊包含錯誤;

for (int i = 0; i < userArray.length; i++) { 
    //Give the array the value of the range 
    userArray[arraylength] = range; 
    //Output variables 
    System.out.println(userArray[arraylength]); 
} 

您需要更改arraylengthi

for (int i = 0; i < userArray.length; i++) { 
    //Give the array the value of the range 
    userArray[i] = range; 
    //Output variables 
    System.out.println(userArray[i]); 
} 
相關問題