I can't see why it is not working.
package com.codegym.task.task18.task1828;
/*
Prices 2
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.*;
/*
Prices
*/
public class Solution {
public static class Product {
int id;
String productName;
String price;
String quantity;
public Product(int id, String productName, String price, String quantity) {
this.id = id;
this.productName = productName;
this.price = price;
this.quantity = quantity;
}
}
public static void main(String[] args) throws Exception {
int id;
if (args.length == 0) { return; }
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
Map<Integer, Product> products = new LinkedHashMap<>();
try (BufferedReader fileReader = new BufferedReader(new FileReader(fileName))) {
while (fileReader.ready()) {
Product product = getProduct(fileReader.readLine());
products.put(product.id, product);
}
}
switch (args[0]) {
case "-c":
id = products.keySet().stream().max(Integer::compareTo).orElse(0);
products.put(id, getProduct(++ id, args));
break;
case "-u":
id = Integer.parseInt(args[1]);
products.put(id, getProduct(id, args));
break;
case "-d":
id = Integer.parseInt(args[1]);
products.remove(id);
break;
}
try (FileWriter fileWriter = new FileWriter(fileName)) {
for (Product product : products.values()) {
fileWriter.write(product.toString());
fileWriter.write(System.lineSeparator());
}
}
}
/**
* Generate a product from its string representation.
*/
public static Product getProduct(String string) {
return new Product(
Integer.parseInt(string.substring(0, 8).trim()),
string.substring(8, 38).trim(),
string.substring(38, 46).trim(),
string.substring(46, 50).trim());
}
/**
* Generate a product.
*/
public static Product getProduct(int id, String[] args) {
StringBuilder name = new StringBuilder();
int startingIndex = String.valueOf(id).equals(args[1]) ? 2 : 1;
while (startingIndex < args.length - 2) { name.append(args[startingIndex ++]).append(" "); }
String price = args[args.length - 2];
String quantity = args[args.length - 1];
return new Product(
id,
name.length() > 30 ? name.substring(0, 30) : name.toString().trim(),
price.length() > 8 ? price.substring(0, 8) : price,
quantity.length() > 4 ? quantity.substring(0, 4) : quantity
);
}
}