Brian - 2 months ago 18

Java Question

I have in array with some doubles in them. I want to divide them, for example with an array that contains 6.0, 3.0 and 2,0 the result should be 1 (6/3/2). I wrote the following code:

`System.out.print("How many numbers do you want to divide? ");`

int division = input.nextInt();

double[] divisionArray = new double[division];

for(int i = 0; i < division; i++) {

System.out.print("Enter your " + (i + 1) + ". number: ");

divisionArray[i] = input.nextDouble();

}

for(int k = 0; k < division; k ++) {

double resultDivision = divisionArray[k] / divisionArray[k + 1];

}

System.out.println("Result: " + resultDivision);

but that doesn't seem to work. I get the error

`Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2`

Answer

this should work:

```
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
//remember the first value and divide it trough the second,
//third, fourth and so on...
double result = divisionArray[0];
for(int k = 1; k < division; k ++) {
result = result / divisionArray[k];
}
System.out.println("Result: " + result);
}
```