Question originally posted in Spanish, on es.stackoverflow.com, by Fernando Méndez:
Ask for a name to search for, read that name from the keyboard and go through the array to verify if it exists, if it is found, show a message indicating that if the name x is found, otherwise, show a legend, the name x is not found.
This is my code but when executing and comparing the elements it only takes the last element of the array and that is the one that compares the others are omitted.
package arrreglo_practicas; import java.util.Arrays; import java.util.Scanner; import javax.swing.JOptionPane; public class Arrreglo_Practicas { public static void main(String[] args) { Scanner input = new Scanner(System.in); String busqueda = ""; int elements = 0 ; String aux = null ; //tomando el valor e insertarlo en el arreglo elements = Integer.parseInt(JOptionPane.showInputDialog( "digite la cantidad de elementos del areglo ")); //arreglo de "n" elementos String [] arreglo = new String [elements]; //recorriendo el arreglo para que tome los valores for (int x = 0; x <arreglo.length; x++){ System.out.print("|ingresa los nombres| "); aux = input.nextLine(); arreglo[x] = aux; } //búsqueda inicial busqueda = JOptionPane.showInputDialog(null," busca un nombre:"); //parte que se ejecuta mal if (busqueda.equals(aux)){ for (int a = 0; a < aux.length(); a++) System.out.println("si se encuentra el nombre:"); }else { JOptionPane.showMessageDialog(null,"dicho nombre no existe: "); } } }