Détection des doublons de tableau en Java


Je code ce programme qui demande à l'utilisateur. Entrez le nombre d'entiers à trier: (par exemple) 3

input 1: 3
input 2: 3
input 3: 3

En utilisant boolean found = false; dans mon code afin de rechercher un nombre dans le tableau. Si l'utilisateur devra saisir: "Entrez un nombre à rechercher dans le tableau:" (par exemple) 3

L'index de ce nombre sera affiché. J'ai correctement codé cette partie. mais il s'avère que mon programme vérifie le premier élément,chaque fois que j'entre le même numéro. Mais si j'entre comme, 3,4,5. ensuite, recherchez 5. Mon programme afficher l'index du numéro 5.

Alors, que faire si j'ai des doublons? Que dois-je utiliser. Si vous regardez mon code ci-dessous.

boolean found = false;
System.out.println("Enter a number to be search in array:");
    jj = jhay.nextInt();

    for (gremio = 0; gremio < yahj; gremio++) 
    {
        if (array[gremio] == jj) 
        {
            found = true;
            break;
        }
    }
    if (found)
    {
        System.out.println("Found at index " + gremio);

    }
    else
    {
        System.out.println("Not found!");
    }     

Nombres d'entiers à trier: 3 entrée: 3 entrée: 5 entrée: 5

Entier de recherche: 5

"Trouvé à l'index": 1

Mais pourquoi mon programme ne peut pas trouver l'index 2?

C'est tout le code de mon Programme.

package javaapplication1;
import java.util.Scanner;

 public class JavaApplication1 
{
public static void main(String[] args) 
{
    int yahj, gremio, jj, temp;
    boolean found = false;
    Scanner jhay = new Scanner(System.in);

    System.out.print("Enter the number of integers to sort:");
    yahj = jhay.nextInt();

    int array[] = new int[yahj];

    System.out.println("Enter " + yahj + " integers: ");

    for (gremio = 0; gremio < yahj; gremio++) 
    {
        array[gremio] = jhay.nextInt();
    }

    for (gremio = 0; gremio < yahj - 1; gremio++) 
    {
        for (jj = 0; jj < yahj - gremio - 1; jj++) 
        {
            if (array[jj] > array[jj + 1]) 
            {
                temp = array[jj];
                array[jj] = array[jj + 1];
                array[jj + 1] = temp;
            }
        }
    }

    System.out.println("Sorted list of integers in ascending order:");

    for (gremio = 0; gremio < yahj; gremio++) 
    {
        System.out.println(array[gremio]);
    }

    for (gremio = 0; gremio < (yahj - 1); gremio++) 
    {
        for (jj = 0; jj < yahj - gremio - 1; jj++) 
        {
            if (array[jj] < array[jj + 1]) 
            {
                temp = array[jj];
                array[jj] = array[jj + 1];
                array[jj + 1] = temp;
            }
        }
    }
     System.out.println("Sorted list of integers in descending order:");

    for (gremio = 0; gremio < yahj; gremio++) 
    {
        System.out.println(array[gremio]);
    }

    System.out.println("Enter a number to be search in array:");
    jj = jhay.nextInt();

    for (gremio = 0; gremio < yahj; gremio++) 
    {
        if (array[gremio] == jj) 
        {
            found = true;
            break;
        }
    }
    if (found)
    {
        System.out.println("Found at index " + gremio);

    }
    else
    {
        System.out.println("Not found!");
    }     
}

}

Author: jass lol, 2015-12-14

4 answers

Selon ce que vous voulez.

Si vous voulez sortir chaque correspondance, placez l'impression à l'intérieur de la boucle et n'affichez not found que si vous n'avez pas eu de correspondance après la boucle.

boolean found = false;
System.out.println("Enter a number to be search in array:");
jj = jhay.nextInt();

for (gremio = 0; gremio < yahj; gremio++) 
{
    if (array[gremio] == jj) 
    {
        found = true;
        System.out.println("Found at index " + gremio);
    }
}
if (!found) {
    System.out.println("Not found!");
}     

Si vous ne voulez que la dernière correspondance, vous pouvez exclure le break de la boucle, ce qui vous donnerait le dernier index.

boolean found = false;
System.out.println("Enter a number to be search in array:");
jj = jhay.nextInt();

for (gremio = 0; gremio < yahj; gremio++) 
{
    if (array[gremio] == jj) 
    {
        found = true;
    }
}
if (found)
{
    System.out.println("Found at index " + gremio);

}
else
{
    System.out.println("Not found!");
} 
 0
Author: SomeJavaGuy, 2015-12-14 07:23:07

L'instruction break; dans votre condition if casse la boucle dès que vous trouvez la première correspondance. Ainsi, la boucle ne continue plus et le reste de l'élément de tableau ne sont plus recherchés.

  if (array[gremio] == jj) 
            {
                found = true;
                break;
            }

Si vous avez besoin d'imprimer toutes les correspondances possibles, vous pouvez utiliser ce code:

boolean found = false;
System.out.println("Enter a number to be search in array:");
jj = jhay.nextInt();

for (gremio = 0; gremio < yahj; gremio++) 
{
    if (array[gremio] == jj) 
    {
        found = true;
        System.out.println("Match found at index " + gremio);
    }
}
if (!found) {
    System.out.println("Not found!");
}
 0
Author: Haseeb Anser, 2015-12-14 07:26:26

J'ai utilisé votre code, fait quelques modifications, ajouté mes propres variables de test... reportez-vous à ce code pour apporter des modifications au vôtre.

    Scanner jhay = new Scanner(System.in);
    int gremio;
    int[] array = {3, 5, 5};
    boolean found = false;
    System.out.println("Enter a number to be search in array:");
    int jj = jhay.nextInt();

    for (gremio = 0; gremio < array.length; gremio++) {
        if (array[gremio] == jj) {
            found = true;
        }

        if (found) {
            System.out.println("Found at index " + gremio);
        } else {
            System.out.println("Not found!");
        }

        found = false;
    }

J'espère que cela fonctionne

 0
Author: Jeet Parekh, 2015-12-14 07:51:03

Puisque votre tableau est trié, vous pouvez utiliser binary search pour renvoyer tous les index où se trouve la valeur de recherche:

public static <T extends Comparable<? super T>> List<Integer> binSearch(T[] array, T value) {
    List<Integer> found = null;
    int index = Arrays.binarySearch(array, 0, array.length, value, Comparator.naturalOrder());
    if (index < array.length() && array[index].compareTo(value) == 0) {
        found = new ArrayList<>();
        found.add(index);
        for (index++; index < array.length; index++) {
            if (array[index].compareTo(value) == 0) {
                found.add(index);
            }
            else break;
        }
    }
    return found;
}

Remarque Comparateur.naturalOrder ne se trouve que dans l'API Java 8, sinon vous devrez fournir une classe de comparateur personnalisée pour utiliser ce

 0
Author: smac89, 2015-12-14 08:10:57