0

as you can see below I have a variable called costperkm, usually 0.08, then I have an array based on a number, then a second array built around those numbers multiplied by costperkm, but I get the error; 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]);
Kieronboz
  • 85
  • 3
  • 14

3 Answers3

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

Means that you only have 0-4 indexes, so:

distarray[5] = 2690;

Try to access index 5 which is out of the array.

BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
1

Your array size is 5 (0,1,2,3,4).

So index will vary from 0 to 4.

You cant access array[5]. It will throw exception.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
0

Look at below two expressions:

last_index_of_the_array != length_of_the_array    
last_index_of_the_array == length_of_the_array -1

If your array length is 5 your last index will 4

PermGenError
  • 45,977
  • 8
  • 87
  • 106