Hello everybody. I don't catch this situtation. My code isn't verified because of the third condition and the recommendation is "The item with the updated data should be on the same line in the file." But my test show exactly this requirement. Can you help me pointing out my mistake? I'd be glad about any help and thx.
package com.codegym.task.task18.task1828;
/*
Prices 2
*/
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static void main(String[] args) throws Exception {
//ArrayList<Product> productList = new ArrayList<>();
HashMap<Integer, Product> productList = new HashMap<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = br.readLine();
br.close();
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferFile = new BufferedReader(fileReader);
while (bufferFile.ready()) {
String strProduct = bufferFile.readLine();
//System.out.println(strProduct);
Product prod = new Product(strProduct);
productList.put(prod.id, prod);
}
if((args.length>0) &&(args[0].equals("-d"))){
int idToDelete = Integer.parseInt(args[1]);
productList.remove(idToDelete);
}
int idToUpdate = 0;
Product updateProduct = null;
if((args.length>0) &&(args[0].equals("-u"))){
idToUpdate = Integer.parseInt(args[1]);
String strUpdate = "";
strUpdate = fillWithSpaces(strUpdate, String.valueOf(idToUpdate), 8);
strUpdate = fillWithSpaces(strUpdate, args[2], 30);
strUpdate = fillWithSpaces(strUpdate, args[3], 8);
strUpdate = fillWithSpaces(strUpdate, args[4], 4);
updateProduct = new Product(strUpdate);
//productList.replace(idToUpdate, productList.get(idToUpdate), updateProduct);
}
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
int maxId = 0;
//for (Product prod : productList) {
//prod = null;
for(Map.Entry<Integer, Product> entry : productList.entrySet()) {
Product prod = entry.getValue();
if (prod.id == idToUpdate) {
prod = updateProduct;
}
bufferWriter.write(prod.toString()+"\n");
if (prod.id>maxId) maxId = prod.id;
System.out.println(prod.toString());
}
if((args.length>0) &&(args[0].equals("-c"))){
String newProduct = "";
newProduct = fillWithSpaces(newProduct, String.valueOf(maxId+1), 4);
newProduct = fillWithSpaces(newProduct, args[1], 30);
newProduct = fillWithSpaces(newProduct, args[2], 8);
newProduct = fillWithSpaces(newProduct, args[3], 4);
bufferWriter.write(newProduct);
}
bufferFile.close();
bufferWriter.close();
}
public static String fillWithSpaces(String newLine, String data, int numberOfChars) {
newLine += data;
for (int i=data.length(); i<numberOfChars; i++) {
newLine += " ";
}
return newLine;
}
}