Sorry this is getting routine but I have another question... or better, the mentor has another complaint and I can't fathom what he means or where the problem should be. For my personal condition everything is fine (as always) - you know me already I hope 😜🤪.
By the way, that's the mentors exact notice: The task conditions are not fulfilled.
package de.codegym.task.task18.task1828;
/*
Preise 2
*/
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) throws Exception {
if (args.length < 2) return;
String fileName = null;
try (BufferedReader console = new BufferedReader(new InputStreamReader(System.in))) {
fileName = console.readLine();
}
switch(args[0]) {
case "-c":
addProduct(fileName, args);
break;
case "-u":
updateProduct(fileName, args);
break;
case "-d":
deleteProduct(fileName, args[1]);
break;
}
}
private static void addProduct(String fileName, String[] args) throws IOException {
List<Product> products = readProductList(fileName);
// from the args create the product that should be added to the db and add it to the list as well -> write the list back
products.add(new Product(Product.getNextId(), args[1], args[2], args[3]));
writeProductList(fileName, products);
}
private static void updateProduct(String fileName, String[] args) throws IOException {
List<Product> products = readProductList(fileName);
long id = Long.parseLong(args[1]);
Product p = getProduct(id, products);
p.setProductName(args[2]);
p.setPrice(args[3]);
p.setQuantity(args[4]);
writeProductList(fileName, products);
}
private static void deleteProduct(String fileName, String strId) throws IOException {
int id = Integer.parseInt(strId);
List<Product> products = readProductList(fileName);
Product p = getProduct(id, products);
if (products.remove(p)) // if we successfully removed the entry -> just in that case rewrite the db
writeProductList(fileName, products);
}
// helper methods - read/ write db to a list, get product with id
private static void writeProductList(String fileName, List<Product> products) throws IOException {
try (PrintWriter out = new PrintWriter(fileName)) {
products.forEach(out::println);
}
}
private static List<Product> readProductList(String fileName) throws IOException {
List<Product> products = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
while (in.ready())
products.add(new Product(in.readLine()));
}
return products;
}
private static Product getProduct(long id, List<Product> products) {
return products.stream()
.filter(e -> e.getId() == id)
.findFirst()
.orElseThrow(RuntimeException::new);
}
}