java使用数组内部的乘法从另一个数组填充数组
正如你在下面看到的,我有一个叫做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]);
# 1 楼答案
这意味着您只有0-4个索引,因此:
尝试访问数组外的索引5
# 2 楼答案
你的数组大小是5(0,1,2,3,4)
所以索引将在0到4之间变化
您无法访问数组[5]。它将抛出异常
# 3 楼答案
请看下面两个表达:
如果数组长度为5,则最后一个索引将为4