简体   繁体   中英

Add and subtract values from a single array Java

I am having trouble subtracting values from a single array. If I have the numbers 1, 2, 3, 4, 5 stored in an array, how can I find the difference?

For example 1-2-3-4-5 = -13

I know how to sum the values of an array but having trouble subtracting one array element from the next to get the correct answer.

int sum = 0;

if (operator == '+'){
  for ( int j = 0; j < intArray.length; j++ ) {
    sum += intArray[j]; 
  }
}
if (operator == '-'){
  for ( int j = 0; j < intArray.length; j++ ) {
    sum += intArray[j] - intArray[j+1] ; 
  }
}

System.out.println("The answer is " + sum);

//This is a pretty simple way to solve it

public class Minimize {

        public static int substractArrayValues(int [] q){
            int val=0;
            for (int i=0; i<q.length; i++){

                if (i==0){
                    val=q[i];
                }
                else {
                    val=val-q[i];
                }
            }
            return val;

        }

        public static void main(String[] args) {

            int [] q={1,2,3,4,5};

            System.out.println(substractArrayValues(q));
        }

    }

This will print -13

I assume you want to subtract 1-2-3-4-5 which is equal to -13.

So here comes your mistake sum+=intArray[j] - intArray[j+1] ;

Operation:-

         Iteration 1:- sum=-1       which is     (1-2)       sum=-1

         Iteration 2:sum=sum+(2-3)  which is     (-1+2-3)    sum=-2

         Iteration 3:sum=sum+(3-4)  which is     (-2+3-4)    sum=-3

         Iteration 4:sum=sum+(4-5)  which is     (-3+4-5)    sum=-4

         Iteration 5:sum=sum+(5-Garbage value or indexoutofbound exception)         
          sum=garbage value

Try using sum-=intArray[j];

With IntStream and a bit of functional programming

import java.util.Arrays;
import java.util.stream.IntStream;
int myArray[] = {1,2,3,4,5};
int sum = IntStream
          // get all the indices
          .range(0, myArray.length) 

          // for the 1st element use the +ve sign 
          // and for the rest use -ve sign: so it 
          // will generate 1,-2,-3,-4,-5
          .map(i -> i == 0? myArray[i] : -myArray[i]) 

          // add the generated elements using map: 1-2-3-4-5
          .sum(); 

System.out.println(sum); // -13

You should start with a the sum at index 0 and then call -= to all the other elements. currently you are doing index - (index -1) which will fail since you don't check for out of bounds. Also the math will be wrong in your current implementation because you use values to subtract twice instead on once.

Take this array with your subtraction method A[1, 2, 3, 4]

sum = 0;
sum += 1 - 2;
sum is -1; (Correct)
sum += 2 - 3;
sum is (-1 + -1) = -2 (Wong, should be -4)
sum += 3 - 4;
sum is (-2 - 1) = -3 (Wrong should be -8)
sum += 4 - A[4] (ERROR index out of bounds)

Here is the implementation that subtracts the values once

if (operator == '-'){
  sum = intArray.length > 0 ? intArray[0] : 0;
  for ( int j = 1; j < intArray.length; j++ ) {
    sum -= intArray[j]; 
  }
}

You always do a positive sum += on operator - . But how about using the Stream -API instead?

IntStream.of(1, 2, 3, 4, 5)
         .reduce(operatorFunction('-'))
         .ifPresent(System.out::println);

with the following IntBinaryOperator -returning function:

static IntBinaryOperator operatorFunction(char operator) {
  if (operator == '-') {
    return (int1, int2) -> int1 - int2;
  }
  return (int1, int2) -> int1 + int2;
}

which prints -13 as you would expect. This is all you need. Note that you could also use IntStream.sum to achieve a simple sum. With the operatorFunction however you could also add * or ÷ later if you wish.

Another way to write the above code (with intermediate values):

int[] yourInputArray = {1, 2, 3, 4, 5};
char operator = '-';
OptionalInt = Stream.of(yourInputArray)
                    .reduce(operatorFunction(operator));

From here you can call orElse(0) or throw an exception with orElseThrow(() -> ...) , etc. Just have a look at the OptionalInt -javadoc for your options. As soon as you move away from the primitive int you may want to exchange the code by using Stream , BinaryOperator<Integer> and Optional<Integer> .

By the way, there is also an IndexOutOfBoundException in your current code. But why messing with indexes and arrays, if you can use Stream s and so few lines of code?

We have to take the first value in the array, and then subtract or add the remaining values from and to it depending on the operator. This is done as shown below:

int sum, dif;
if(intArray.length >= 1){
  sum = intArray[0];
  dif = intArray[0];
}
if (operator == '+'){
   if(intArray.length > 1){
     for ( int j = 1; j < intArray.length; j++ ) {
       sum += intArray[j]; 
     }
   }
   System.out.println("The sum is = " + sum);
}
if (operator == '-'){
  if(intArray.length > 1){
    for ( int j = 1; j < intArray.length; j++ ) {
      dif -= intArray[j]; 
    }
  }
  System.out.println("The difference is = " + dif);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM