簡體   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