没有 space beetwen 值 txt java
no space beetwen values txt java
代码工作正常,除了一个问题。加薪后 space 的 beetwen 值消失了,然后我的程序就不能正常工作了。
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();
我想知道问题出在哪里以及为什么space没有添加
你正在丢失 space 因为 line.substring(0, line.lastIndexOf(" "))
将 return 一个子字符串直到最后一个 space 不包括 space 所以你可以添加一个space 在 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)
代码工作正常,除了一个问题。加薪后 space 的 beetwen 值消失了,然后我的程序就不能正常工作了。
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();
我想知道问题出在哪里以及为什么space没有添加
你正在丢失 space 因为 line.substring(0, line.lastIndexOf(" "))
将 return 一个子字符串直到最后一个 space 不包括 space 所以你可以添加一个space 在 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)