Home > OS >  no space beetwen values txt java
no space beetwen values txt java

Time:04-06

Code works fine, except one problem. After increasing salary the spaces beetwen values disapears and then my programm doesn't work well.

Joe 2022/04/05 HR-Manager44200
Steve 2022/04/06 Admin 100000
Scanner console = new Scanner(System.in); 
System.out.print("Name of employee : "); 
String pID = console.nextLine(); System.out.print("Allowance : "); 
replenish = console.nextInt();    
File originalFile = new File("worker.txt");
    BufferedReader br = new BufferedReader(new FileReader(originalFile));

    File tempFile = new File("tempfile.txt");
    PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

    String line = null;
    while ((line = br.readLine()) != null) {

        if (line.contains(pID)) {
            String strCurrentSalary = line.substring(line.lastIndexOf(" "));
            if (strCurrentSalary != null || !strCurrentSalary.trim().isEmpty()) {
                int replenishedSalary = Integer.parseInt(strCurrentSalary.trim())   replenish;
                System.out.println("Sum with added : "   replenishedSalary);
                line = line.substring(0, line.lastIndexOf(" "))   replenishedSalary;
            }

        }
        pw.println(line);
        pw.flush();
    }
    pw.close();
    br.close();

I want to know where is the problem and why space doesn't adding

CodePudding user response:

You are losing the space because line.substring(0, line.lastIndexOf(" ")) will return a substring up to the last space not including the space so you could add a space after line.substring(0, line.lastIndexOf(" ")) like below.

line = line.substring(0, line.lastIndexOf(" "))   " "   replenishedSalary;

Also you can use String.format to crate the line as below.

line = String.format("%s %d",line.substring(0, line.lastIndexOf(" ")),replenishedSalary)
  • Related