Multiply value in array

Asked

Viewed 300 times

0

How do I multiply the elements of an array? what am I doing wrong?

For example, if I have:

int numbers[]={1,2,2,4,5,6};

and my card_block is 2, the restutado would 1x4x5x6=120;

int countCards(int [] cards, int BLOCK_CARD){
  int quant=0;
  int count =0;
  for (int i=0; i<cards.length; i++){
   if(cards[i]!=BLOCK_CARD)
  count=cards[i];
  count=count*cards[i];

   quant=count;
  }
  return quant;
}
  • What logic are you trying to apply ? Each time you are on the blocked card you are supposed to multiply by the last before the blocked one or simply ignore the card ?

2 answers

0


A leaner way would be to use the features of Java 8. You could use Streams and its operators.

 int countCards(int [] cards, int BLOCK_CARD){
     return IntStream.of(cards)
                .filter(s -> s != BLOCK_CARD)
                .reduce(1, (a, b) -> a * b);
 }

Just licking, using streams includes the stream itself that derives from a collection, then the intermediate operations that always result in a new stream and the terminal operation, which terminates and returns a result.

A link with an overview of Stream you can see here.

0

Try it like this:

  int countCards(int [] cards, int BLOCK_CARD){
  int quant=0;
  int count =1;
  for (int i=0; i<cards.length; i++){
   if(cards[i]!=BLOCK_CARD){

  count=count*cards[i];
}
   quant=count;
  }
  return quant;
}
  • Thank you, that’s right!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.