-1

I have an array that holds two doubles. I need to subtract number b from number a.

e.g. 30(number a) - 10(number b)

How do I iterate through my ArrayList and subtract these two numbers? I am not sure if I would need to iterate backwards or forwards.

My code so far. Does not produce the correct result, I am aware d - d would return 0 but I am unsure what to do here:

for (double d = numbersEnteredArrayList.size() - 1; d >= 0; d--) {
    equals = d - d;
    System.out.println(equals);
}
Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
James B
  • 221
  • 3
  • 14

3 Answers3

0

I'm not sure why you are using an array to store two numbers, but if you just need to subtract them you can access them directly.

double diff = numbersEnteredArrayList.get(1) - numbersEnteredArrayList.get(0);
user1875195
  • 968
  • 4
  • 8
  • 22
0

You can loop through the array in either direction.

Are you trying to output the difference of every sequential pair? If the array was [6 4 2 7] and you want to calculate and display 2 2 -5 (6-4)(4-2)(2-7) then just have the for loop start at 0, go until ArrayList.size()-1 and compute numbersEnteredArrayList.get(d) - numbersEnteredArrayList.get(d+1)

Doug
  • 140
  • 10
-1

You can keep track of the first value in the array using an int variable then keep subtracting from it as you iterate through the array (of course you would skip the first index).

Bazinga
  • 489
  • 1
  • 5
  • 16