Сделала по аналогии с предыдущей задачей, но валидатор не пропускает. Подсказка от ментора
"Требование задачи не выполнено."
хотя данные в файле обновляются.
package com.javarush.task.task18.task1828;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
Прайсы 2
*/
public class Solution {
public static class Product {
int id;
String name;
String price;
String quantity;
public Product(int id, String name, String price, String quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
@Override
public String toString() {
return String.format("%-8d%-30s%-8s%-4s", id, name, price, quantity);
}
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
List<Product> products = new ArrayList<>();
try (BufferedReader fileReader = new BufferedReader(new FileReader(fileName))) {
while (fileReader.ready()) {
Product product = getProduct(fileReader.readLine());
products.add(product);
}
}
switch (args[0]) {
case "-u":
for (int i = 0; i < products.size(); i++) {
Product product = getProduct(products.get(i).toString());
if (product.id == Integer.parseInt(args[1])) {
String name = "";
for (int j = 1; j < args.length - 2; j++) {
name += args[j] + " ";
}
if (name.length() > 30) {
name = name.substring(0, 30);
}
String price = args[args.length - 2];
if (price.length() > 8) {
price = price.substring(0, 8);
}
String quantity = args[args.length - 1];
if (quantity.length() > 4) {
quantity = quantity.substring(0, 4);
}
Product product1 = new Product(product.id, name.trim(), price, quantity);
products.set(i, product1);
}
}
try (FileWriter fileWriter = new FileWriter(fileName)) {
for (Product product: products ) {
fileWriter.write(product.toString()+"\n");
}
}
break;
case "-d":
for (int i = 0; i < products.size(); i++) {
Product product = getProduct(products.get(i).toString());
if (product.id == Integer.parseInt(args[1])) {
products.remove(i);
}
}
try (FileWriter fileWriter = new FileWriter(fileName)) {
for (Product product: products ) {
fileWriter.write(product.toString()+"\n");
}
}
break;
}
}
public static Product getProduct(String string) {
String id = string.substring(0, 8).trim();
String name = string.substring(8, 38).trim();
String price = string.substring(38, 46).trim();
String quantity = string.substring(46).trim();
return new Product(Integer.parseInt(id), name, price, quantity);
}
}