Reputation:
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: "); } } }
Upvotes: 2
Views: 148
Reputation: 4592
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;
Upvotes: 2