【问题标题】:no space beetwen values txt java值之间没有空格 txt java
【发布时间】:2022-11-04 15:46:44
【问题描述】:

代码工作正常,除了一个问题。增加薪水后,值之间的空格消失了,然后我的程序就不能正常工作了。

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();

我想知道问题出在哪里以及为什么没有增加空间

【问题讨论】:

  • 当你在这里使用line.lastIndexOf(" ") line.substring(0, line.lastIndexOf(" ")) 时它不包含空格,所以你需要在子字符串结束索引line.substring(0, line.lastIndexOf(" ") +1) 中添加+1 或手动添加空格line = line.substring(0, line.lastIndexOf(" ")) + " " + replenishedSalary;

标签: java txt


【解决方案1】:

您正在丢失空间,因为line.substring(0, line.lastIndexOf(" ")) 将返回一个子字符串,直到最后一个空格不包括空格,因此您可以在line.substring(0, line.lastIndexOf(" ")) 之后添加一个空格,如下所示。

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

您也可以使用String.format 创建如下行。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-11
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2018-10-12
    • 2013-09-24
    相关资源
    最近更新 更多