Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
How do I look for an element in a array string java

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: ");
        }
         
    }
    
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You need to check the equality inside the for loop one by one with each input array value.

//parte que se ejecuta mal
     boolean isMatch = false;
    
        for (int a = 0; a < arreglo.length; a++) {
          if (busqueda.equalsIgnoreCase(arreglo[a])) {
            isMatch = true;
            System.out.println("si se encuentra el nombre:");
          }
        }
    
        if (!isMatch)
    
        {
          JOptionPane.showMessageDialog(null, "dicho nombre no existe: ");
        }

Java 8 (as suggested by paulsm4 in comments):

In Java8 with Stream you can do as below:

//parte que se ejecuta mal
    final Optional<String> optionalMatched = Arrays.stream(arreglo).filter(a -> a.equalsIgnoreCase(busqueda))
        .findFirst();

    if (optionalMatched.isPresent()) {
      System.out.println("si se encuentra el nombre:");
    } else {
      JOptionPane.showMessageDialog(null, "dicho nombre no existe: ");
    }

But additionally you would need to update the busqueda declaration as below to make it final.

String busqueda;
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda