0

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

2
  • 1
    You're assigning sum each iteration in the loop. Also, I'm not sure what the point of sum -= sum - nums[i+1] is because you're subtracting sum from itself. Commented May 28, 2019 at 15:15
  • 2
    Run the loop line by line to see what it is doing, if the logic isn’t clear from the code itself. You’re assigning sum at every iteration, which probably isn’t what you want. And the line sum -= sum - nums[i+1] doesn’t seem rational because it basically means sum = sum + nums[i+1] Commented May 28, 2019 at 15:15

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't generate the correct result for obvious reasons. Please test your code.
0

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);
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.