Original:
19847 Swim trunks, blue 159.00 12
198479 Swim trunks, black with printe173.00 17
19847983Snowboard jacket with reflecti10173.991234
Without using "-c":
19847 Swim trunks, blue 159.00 12
198479 Swim trunks, black with printe173.00 17
19847983Snowboard jacket with reflecti10173.991234
Using "-c":
String[] args = {"-c","Test using -c","19.00","123"};
19847 Swim trunks, blue 159.00 12
198479 Swim trunks, black with printe173.00 17
19847983Snowboard jacket with reflecti10173.991234
19847984Test using -c 19.00 123
package com.codegym.task.task18.task1827;
/*
Prices
*/
import java.io.*;
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) throws Exception {
//lines stores every line in file
ArrayList<String> lines = new ArrayList<>();
String fileName = (new BufferedReader(new InputStreamReader(System.in))).readLine();
//Read entire file
BufferedReader reader = (new BufferedReader(new FileReader(new File(fileName))));
while (reader.ready()) {
lines.add(reader.readLine());
}
reader.close();
//If args[0] == "-c", create new line
if (args[0].equals("-c")){
//Get lastid
String lastline;
if (lines.size()>0) lastline = lines.get(lines.size()-1);
else lastline = "00000000";
//ids = lastid+1 -> to string -> add spaces
String id = String.valueOf(Integer.parseInt(lastline.substring(0,8))+1);
String ids = id + (new String(new char[8-id.length()]).replace('\0', ' '));
//Add spaces where needed
String product = args[1] + (new String(new char[30-args[1].length()]).replace('\0', ' '));
String price = args[2] + (new String(new char[8-args[2].length()]).replace('\0', ' '));
String quantity = args[3] + (new String(new char[4-args[3].length()]).replace('\0', ' '));
//Add the new line
lines.add(ids+product+price+quantity);
}
//Write to file
BufferedWriter writer = (new BufferedWriter(new FileWriter(new File(fileName))));
for (int i=0; i<lines.size(); i++){
writer.write(lines.get(i));
//Call "Enter" to go to new line (I tried without -1 too)
if (i<lines.size()-1) writer.write("\n");
}
writer.close();
}
}