Hi I have a problem with my code, during tests, it seems like it works for UPDATE and DELETE but the validation fails at the point with deleting a row. I tested it in different ways - to delete the first line, the line at the bottom, the last line and the output is correct for all of them. Do you have any clue what can be improved?
package pl.codegym.task.task18.task1828;
/*
Ceny 2
*/
import java.io.*;
import java.nio.Buffer;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
//REQ 2 If you run the program without arguments, the list of products must remain unchanged.
if (args.length == 0) return;
//REQ 1 The program should read the file name for CrUD operations from the console.
Scanner sc = new Scanner(System.in);
String fileName = sc.nextLine();
//Preparing the arguments
String choice = args[0];
String id = args[1];
String productName = args[2];
String price = args[3];
String quantity = args[4];
String liner = String.format("%-8s%-30s%-8s%-4s", id, productName, price, quantity);
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
//Below we will read the data from a file and fulfill MAP with it where ID will be a key
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
int idFromFile = 0;
String line;
while ((line = bufferedReader.readLine()) != null) {
idFromFile = Integer.parseInt(line.substring(0, 8).trim());
map.put(idFromFile, line);
}
//REQ3 in case where the first argument is -u iterate through the MAP to find if given id exists to update line
//REQ4 in case where the first argument is -d iterate through the MAP to find if given id exists to delete line
switch (choice) {
case "-u":
for (Map.Entry<Integer, String> entry : map.entrySet()) {
if (Integer.parseInt(id) == entry.getKey()) {
map.put(Integer.parseInt(id), liner);
break;
}
}
break;
case "-d":
for (Map.Entry<Integer, String> entry : map.entrySet()) {
if (Integer.parseInt(id) == entry.getKey()) {
map.remove(Integer.parseInt(id));
break;
}
}
break;
}
//iterate over the MAP to complement the file with updated values
FileWriter fileWriter = new FileWriter(fileName);
for (Map.Entry<Integer, String> entry : map.entrySet()) {
fileWriter.write(entry.getValue());
fileWriter.write("\n");
fileWriter.flush();
}
//REQ5 close streams
fileWriter.close();
fileReader.close();
sc.close();
bufferedReader.close();
}
}