Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

no space beetwen values txt java

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading