Compare elements of an array of integers

0

I need to compare in an array if the number that was digitized is repeated if it is so pull message number is repeated and enter a new one,

    int i, n;

    n = Integer.parseInt(
    JOptionPane.showInputDialog(null," Digite la cantidad de campos para el vector "));

    int Vect1[] = new int[n];

    for(i=0;i<n;i++){
                    Vect1[i] = Integer.parseInt(
         JOptionPane.showInputDialog(null,
         "Digite el valor del vector  en la posicion " +
         "[" + i + "]" ));
    }

I've already tried it in several ways but the IF only works if I specify the field Vect1 [0] Vect1 [1],

    
asked by user75810 17.02.2018 в 22:23
source

2 answers

0

Your problem is not difficult, with the help of some if and the use of for you could have solved it easily. I have given a little head myself to help you and I have solved it quickly.

Solution:

int n;

n = Integer.parseInt(
JOptionPane.showInputDialog(null," Digite la cantidad de campos para el vector "));

int Vect1[] = new int[n];

    for(int i = 0; i < n; i++){
        Vect1[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Digite el valor del vector en la posición " + "[" + i + "]" ));

        // Si "i" es diferente de 0 ya que no habrá ningún valor con que compararlo
        if (i != 0) {
            // comparar el valor digitado con el valor de todas las posiciones existentes del array
            for(int z = 0; z < i; z++) {
                if (Vect1[i] == Vect1[z]) { // si encuentra uno repetido entra aquí
                    // preguntar por un valor nuevo
                    Vect1[i] = Integer.parseInt(JOptionPane.showInputDialog(null, "Número repetido, digite otro valor del vector en la posición " + "[" + i + "]" ));
                }
            }
        }
}

I've tried it very quickly and it works well, if you get to find an error, surely you can fix it. Your problem was to think a little carefully, nothing great.

I hope I have helped you, regards!

    
answered by 17.02.2018 в 23:09
-1

Hello here is my object-oriented solution. First we created this method

  boolean comparar(int vector[],int posicionFinal,int numero){ // Bueno este es un metodo que nos servira para hacer el recorrido del vector hasta la posicion en donde nos encontremos para evitar problemas de null pointer
    for(int i=0;i<posicionFinal;i++){
        if(vector[i]==numero){ //hacemos una comparacion para saber si el numero ingresado ya se ha repetido, si es asi retornamos un true ya que pues la comparacion dio verdadero
            return true;
        }
    }
    return false; // si al final del ciclo no se encontro ninguna coincidencia en el numero pues retornamos un false ya que la comparacion dio falso
}

Then we create the method where the process will be executed

 public void proceso() {
    int tamaño;
    int i; 
    int numero;
    boolean primero = true; //variable para saber si estamos en la primera casilla del arreglo
    boolean repetido;
    tamaño = Integer.parseInt(JOptionPane.showInputDialog("Digite el tamaño del vector")); // Determina el tamaño del vector
    int vector[] = new int[tamaño];

    for(i=0;i<tamaño;i++){
        if(!primero){ // preguntamos si no es la primera posicion del arrelo para asi evitarnos una iteracion de mas en la comparacion
            numero = Integer.parseInt(JOptionPane.showInputDialog("Digite un numero")); // pedimos el ingreso del numero
            repetido = comparar(vector,i,numero); // le metemos a nuestra variable "repetido" lo que contenga el resultado de comparar el numero con nuestro metodo
            while(repetido==true){ // ahora haremos un ciclo mientras que repetido sea igual a verdadero osea mientras el usuario siga agregando numeros existentes pues le pediremos que ingrese uno nuevo
                numero = Integer.parseInt(JOptionPane.showInputDialog("Numero "+numero+" repetido, escriba otro numero")); // le notificamos al usuario que el numero ya esta repetido y que ingrese otro
                repetido = comparar(vector,i,numero);//volvemos a comparar ahora con el nuevo numero que ingreso el usuario arribita
            }
            vector[i] = numero; // si el numero no esta repetido pues lo asignamos a la casilla del vector correspondiente
        }else{ // si estamos en la primera posicion del vector simplemente agregamos el numero a la casilla 0.
            numero = Integer.parseInt(JOptionPane.showInputDialog("Digite un numero"));
            vector[i] = numero;
            primero = false;
        }
    }
    //imprimimos el vector resultante
     for(i=0;i<tamaño;i++){
         System.out.println(vector[i]);
     }

}

Finally we create an instance of the class and call the method "process".

 public static  void main(String args[]){
    Soverflow ejemplo = new Soverflow();
    ejemplo.proceso();
}

It could even be done recursively but that is another story, I hope you serve and greetings.

    
answered by 20.05.2018 в 08:38