Add search by name

main
CPlaiz 2025-12-13 18:20:04 +01:00
parent 95ad6006fe
commit fb64d82bb9
3 changed files with 21 additions and 6 deletions

View File

@ -45,16 +45,12 @@ public class Main {
} }
public static ArrayList<String> readFile(String path) throws FileNotFoundException { public static ArrayList<String> readFile(String path) throws FileNotFoundException {
ArrayList<String> lines = new ArrayList<>(); ArrayList<String> lines = new ArrayList<>();
Scanner sc = new Scanner(new File(path)); Scanner sc = new Scanner(new File(path));
while (sc.hasNextLine()) { while (sc.hasNextLine()) {
lines.add(sc.nextLine()); lines.add(sc.nextLine());
} }
sc.close(); sc.close();
return lines; return lines;
} }
} }

View File

@ -2,7 +2,6 @@ package org.example;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Set;
public class Shop { public class Shop {
@ -41,6 +40,19 @@ public class Shop {
return null; return null;
} }
public Product getProductByNameSearch(String name) {
Product foundProduct = null;
for (Product product : products.keySet()) {
if (product.name.toLowerCase().contains(name.toLowerCase())) {
if (foundProduct != null) {
return null;
}
foundProduct = product;
}
}
return null;
}
public List<Product> getProductList() { public List<Product> getProductList() {
return products.keySet().stream().toList(); return products.keySet().stream().toList();
} }

View File

@ -29,7 +29,14 @@ public class TUI {
case "checkout" -> checkout(null); case "checkout" -> checkout(null);
case "list" -> listProducts(shop.products); case "list" -> listProducts(shop.products);
case "cart" -> listCart(shop.getCart()); case "cart" -> listCart(shop.getCart());
case "add" -> shop.addProductToCart(shop.getProductById(Integer.parseInt(tokens[1]))); case "add" -> {
try {
shop.addProductToCart(shop.getProductById(Integer.parseInt(tokens[1])));
} catch (NumberFormatException e) {
Product productByName = shop.getProductByNameSearch(tokens[1]);
shop.addProductToCart(productByName);
}
}
case "remove" -> shop.removeProductFromCart(shop.getProductById(Integer.parseInt(tokens[1]))); case "remove" -> shop.removeProductFromCart(shop.getProductById(Integer.parseInt(tokens[1])));
case "set" -> case "set" ->
shop.setProductQuantityInCart(shop.getProductById(Integer.parseInt(tokens[1])), Integer.parseInt(tokens[2])); shop.setProductQuantityInCart(shop.getProductById(Integer.parseInt(tokens[1])), Integer.parseInt(tokens[2]));