值之间没有空格 txt java
代码工作正常,除了一个问题。加薪后,值之间的空间消失了,然后我的程序就无法正常工作。
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();
我想知道问题出在哪里以及为什么空间没有增加
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在丢失空间,因为
line.substring(0, line.lastIndexOf(" "))
将返回直到最后一个空格的子字符串,不包括空格,因此您可以在line 之后添加空格.substring(0, line.lastIndexOf(" "))
如下所示。您也可以使用
String.format
创建如下行。You are losing 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 afterline.substring(0, line.lastIndexOf(" "))
like below.Also you can use
String.format
to create the line as below.