【问题标题】:How do I look for an element in a array string java如何在数组字符串java中查找元素
【发布时间】:2020-11-19 07:05:13
【问题描述】:

问题来自posted in Spanish, on es.stackoverflow.com,来自Fernando Méndez

询问要搜索的名称,从键盘上读取该名称并开始 通过数组来验证是否存在,如果找到,显示一个 指示如果找到名称 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: ");
        }
         
    }
    
}

【问题讨论】:

    标签: java arrays arraylist


    【解决方案1】:

    您需要对每个输入数组值一一检查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(如 cmets 中的 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;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    相关资源
    最近更新 更多