Its not test passing the requirements from 3-6 and also i have tried with some inputs in the arguments but it's throwing a StringIndexOutOfBoundsException
-c apple 20000 4
but its not working.
package com.codegym.task.task18.task1827;
/*
Prices
1. The program should read a file name for CrUD operations from the console.
2. The Solution class should not use static variables.
3. When you run the program without arguments, the product list must remain unchanged.
4. When the program is run with the arguments "-c productName price quantity", a new line with the corresponding product should be added to the end of the file.
5. The product must have the next id after the maximum id found in the file.
6. The format of the new product line must precisely match that format specified in the task.
7. The file streams must be closed.
*/
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
if(args[0].equals("-c")){
addLine(s,args);
}
if (args.length==0) return;
//if(args.length==0) return;
br.close();
}
public static void addLine(String filename, String[] arg) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
List<String> list = new LinkedList<>();
while (br.ready()) {
String data = br.readLine();
list.add(data);
}
int id = Integer.parseInt(list.get(list.size()-1).substring(0,8));
String productName = arg[1];
String price = String.valueOf(Double.parseDouble(arg[2]));
String quantity = String.valueOf(Integer.parseInt(arg[3]));
if (productName.length() < 30) {
productName +=" " ;
}
if (price.length() < 8) {
price +=" ";
}
if (quantity.length() < 4) {
quantity +=" ";
}
byte[] bytes = (id+productName+price+quantity).getBytes();
FileWriter fileWriter = new FileWriter(filename);
for (String i : list) {
fileWriter.append(i).append("\n");
}
fileWriter.write(Arrays.toString(bytes));
br.close();
fileWriter.close();
}
}