I have the following ArryList of a Product class which has variable name and code, and a method getCodigo().
ArrayList<Producto> listaProductos = new ArrayList<>();
listaProductos.add("pantalon", "p01");
listaProductos.add("Poleron", "p02");
listaProductos.add("Lechuga", "veg01");
The user will enter a code and I want to evaluate if that code exists or not in the Array.
System.out.println("Por favor ingrese el codigo del producto");
String codigoProducto = entrada.nextLine();
for (Producto productos : listaProductos) {
if(codigoProducto.equals(productos.getCodigo())){
System.out.println("Existe");
}else {
System.out.println("No existe");
}}
If I enter a wrong code, it shows me
No existe
No existe
No existe
And if I enter a correct code, for example veg01, it shows me:
No existe
No existe
Existe
How can I solve that? If the element exists, I want it to show me "Exists" and finish the loop, and if it doesn't exist after evaluating all the elements, just show me "Doesn't exist" and not 3. Thanks
The mistake you are making is that you are printing for each item in the list. You should compute a flag to see if there is or isn't and then print.
Classic:
The way with streams, which gives a shorter code is: