简体   繁体   English

java - 如何在数组字符串中查找元素

[英]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 :最初由Fernando Méndez 在 es.stackoverflow.com 上用西班牙语发布的问题:

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.要求搜索名称,从键盘读取该名称并遍历数组以验证它是否存在,如果找到,则显示一条消息指示如果找到名称 x,否则显示图例,名称找不到 x。

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: "); } } }

You need to check the equality inside the for loop one by one with each input array value.您需要使用每个输入数组值一一检查 for 循环内的相等性。

//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): Java 8(如 paulsm4 在评论中所建议的):

In Java8 with Stream you can do as below:在带有 Stream 的 Java8 中,您可以执行以下操作:

//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.但另外,您需要更新busqueda声明如下以使其成为最终版本。

String busqueda;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM