繁体   English   中英

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

[英]How do I look for an element in a array string java

最初由Fernando Méndez 在 es.stackoverflow.com 上用西班牙语发布的问题:

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

这是我的代码,但是在执行和比较元素时,它只需要数组的最后一个元素,而忽略其他元素的比较。

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

您需要使用每个输入数组值一一检查 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(如 paulsm4 在评论中所建议的):

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

但另外,您需要更新busqueda声明如下以使其成为最终版本。

String busqueda;

暂无
暂无

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

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