code of an Array

2

2) returns the value 0 instead of the correct value 1. "If someone could explain why, it would be helpful.

The code is as follows:

public static int maxNumRepeated(Integer[] a, Integer elem)  {

} // of utils

    
asked by jeyXD 13.09.2018 в 22:15
source

2 answers

0

Hi, reorganize your logic a bit since you were using the Boolean.

public static int maxNumRepeated(int[] a, int elem)  {
  int contador=0;    
  int contadorMax=0;
  boolean encontrado=false;

  if (a==null) {
      return 0;           
  }//de if    

  for (int i=0; i<a.length;i++) {     
      if (a[i]==elem) {
         contador++;

         if (a.length == i + 1)
            encontrado = true;
      }//de if
      else
      {
        if (contador > 0)
        {
          encontrado = true;
        }
        else
        {
         encontrado = false;
        }
      }

      if (encontrado)
      {
        contadorMax = Math.max(contador, contadorMax);
        contador = 0;
        encontrado = false;
      }
  }// de for      
  return contadorMax;  
}

First of all, if you find it, you will find it here, we will find two cases when there is only one element or when it is the last one.

if (a.length == i + 1)
            encontrado = true;

for that I use that validation.

later when it detects a change the counter is validated:

if (contador > 0)
        {
          encontrado = true;
        }
        else
        {
         encontrado = false;
        }

if it is greater than zero, it is marked as found, otherwise it is marked as not found.

At the end, using the Boolean variable, now I apply the max

if (encontrado)
      {
        contadorMax = Math.max(contador, contadorMax);
        contador = 0;
        encontrado = false;
      }

I hope the modifications are understandable. I am not an expert, I imagine that it should be able to do it more efficiently.

    
answered by 14.09.2018 / 22:35
source
0

Hello friend, try this for.

 for (int i=0;i<a.length ;i++) {
          if (a[i]==elem) {
              contador++;
          }

The error is because you put <= , so you are looking at a position that does not exist remember that the positions are the size - 1.

    
answered by 13.09.2018 в 22:27