【发布时间】: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;