jacksonaune
jacksonaune

Reputation: 1

Coding a subtraction loop that takes in a list

I am making a calculator and need a subtraction loop for the code to work. Right now it is scanning the list but only doing the first and last numbers not the entire list.

if(a.equals("Subtract")) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        System.out.println("Enter integers one at a time in order");
        System.out.println("When completed type done");
        while (scan.hasNextInt()) {
            list.add(scan.nextInt());
        }
        Integer[] nums = list.toArray(new Integer[0]);
        for (int i = 0; i < nums.length-1; i++) {
            sum = nums[0];
            sum = sum - nums[i+1];
        }
        System.out.println("Your total is " + sum);
        System.out.println("-----------------------------");
        main(args);
        }

Only subtracts the first and last numbers of loop not entire loop in order

Upvotes: 0

Views: 600

Answers (3)

Conffusion
Conffusion

Reputation: 4475

You're almost there. Move the assignment of the first value outside the loop and start the loop from the second element of the array (index=1):

sum = nums[0];
for (int i = 1; i < nums.length; i++) {
    sum = sum - nums[i];
}

EDIT: Thanks Joakim for your remark. Fixed the end condition in the for loop

Upvotes: 1

Dave Costa
Dave Costa

Reputation: 48111

You're re-initializing sum on each iteration of the loop, to the value of the first element:

sum = nums[0];

You should do this before the loop.

Upvotes: 0

Joakim Danielson
Joakim Danielson

Reputation: 51892

I suspect Java 8 streams is not what OP is after but for completeness here is a way to make use of the List instead of a for loop using streams

if (!list.isEmpty) {
    sum = list.get(0) - list.subList(1, list.size()).stream().reduce(0,Integer::sum);
}

If a loop is prefered then at least use the list already created

sum = list.get(0);
for (int i = 1; i < list.size(); i++) {
    sum -= list.get(i);
}

Upvotes: 0

Related Questions