2013-04-02 71 views
0

如下所示我有一個名爲costperkm的變量,通常是0.08,然後我有一個基於數字的數組,然後是圍繞這些數字乘以costperkm構建的第二個數組,但我得到錯誤; http://puu.sh/2sxi7從另一個數組中使用乘法填充數組

Scanner costscan=new Scanner(System.in); 
    double costperkm = costscan.nextDouble(); 

double distarray[] = new double[5]; 

    distarray[0] = 850; 
    distarray[1] = 1000; 
    distarray[2] = 1250; 
    distarray[3] = 1275; 
    distarray[4] = 1350; 
    distarray[5] = 2690; 

double costarray[] = new double[5]; 

    costarray[0] = (distarray[0]*costperkm); 
    costarray[1] = (distarray[1]*costperkm); 
    costarray[2] = (distarray[2]*costperkm); 
    costarray[3] = (distarray[3]*costperkm); 
    costarray[4] = (distarray[4]*costperkm); 
    costarray[5] = (distarray[5]*costperkm); 

System.out.print(costarray[0]); 
+0

我不想點擊你的外部鏈接來查看你得到的錯誤 –

+0

你的數組有5個索引,但你試圖訪問6. –

+0

http://docs.oracle.com/javase/tutorial/java/ nutsandbolts/arrays.html – iamnotmaynard

回答

5
double distarray[] = new double[5]; 

意味着你只有0-4索引,所以:

distarray[5] = 2690; 

嘗試訪問索引5是從數組中。

+0

非常感謝非常不能相信我忘記了! – Kieronboz

+0

很高興我可以幫助:) – BobTheBuilder

0

看看下面兩個表達式:

last_index_of_the_array != length_of_the_array  
last_index_of_the_array == length_of_the_array -1 

如果你的數組長度爲5你最後的指數將4

1

你的數組大小爲5(0,1,2,3,4)。

所以索引將從0到4變化。

你不能訪問array [5]。它會拋出異常。