2013-04-02 70 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]。它会抛出异常。