Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda