Problems searching a word in a list

-1

What is the problem with this code?

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;

public class busqueda extends JFrame {

private List<String> nombres=new ArrayList<String>();
private JTextField nombre,_nombre;
private JButton ingrese,buscar,mostrar;

Accion accion=new Accion();
Container ce = getContentPane();
public busqueda() {

    ce.setLayout( new FlowLayout() );

    nombre=new JTextField(10);
    nombre.setEditable(true);
    ce.add(nombre);

    ingrese=new JButton("Ingresar");
    ce.add(ingrese);

    _nombre=new JTextField(10);
    _nombre.setEditable(true);
    ce.add(_nombre);

    buscar= new JButton("Buscar");
    ce.add(buscar);

    mostrar=new JButton("Mostrar");
    ce.add(mostrar);


    ingrese.addActionListener(accion);
    buscar.addActionListener(accion);
    mostrar.addActionListener(accion);

    setSize(200,200);
    setVisible(true);
}

private class Accion implements ActionListener {
    public void actionPerformed( ActionEvent e )
    {
        if(e.getSource()==ingrese) {
            nombres.add(nombre.getText());
            JOptionPane.showMessageDialog(null,nombre.getText()+" Agregado a 
            la Lista");
        }

        if(e.getSource()==buscar) {
            String aux=null;
            for(String n:nombres) {
                if(n==_nombre.getText()){aux=n;}
            }   
            if(aux!=null) 
                JOptionPane.showMessageDialog(null,aux);
            else
                JOptionPane.showMessageDialog(null,"No Encontrado");
        }

        if(e.getSource()==mostrar) {
            String salida="";
            for(String n:nombres) { 
                salida+=("\n"+n);
            }
            JOptionPane.showMessageDialog(null,salida);
        }
    }
} 


public static void main(String[] args) {
    new busqueda();
}

}

I honestly do not understand it, if I add "Maria" and I search for "Maria" she does not find it, if it is a list of integers if she finds them but with the string something is wrong, and I only have this problem when I enter the word for keyboard to search, but working internally with the code (without me entering it) compares me well.

note * Any clarification or suggestion outside the question is well received since I have only a week working with java

    
asked by Marcel Salazar 20.08.2018 в 04:50
source

1 answer

4

Java text strings do not compare to == since String is an object rather than a native type.

To compare an object in java, use objecto.equals(objecto_a_comparar) , then your code would be

for(String n:nombres) {
  if(n.equals(_nombre.getText())){aux=n;}
}   
    
answered by 20.08.2018 / 04:57
source