英文:
Extract a value from a string file and converting it to int with Java
问题
我有一个文本文件(test.txt):
Bob,12,15,20
Ruth,45,212,452
使用Java,我想提取每行的最后一个元素(每个元素由逗号分隔)。
到目前为止,我编写了以下代码:
br = new BufferedReader(new FileReader("test.txt"));
while ((line = br.readLine()) != null) {
String[] facture = line.split(",");
int fquantite = Integer.parseInt(facture[3]);
System.out.println("Amount=" + fquantite);
但是它给我报错。问题是,我知道如何获取数字(例如,我可以写:
System.out.println("Amount=" + facture[3]);
它可以正常工作,但是因为某种原因,我无法将其转换为整数。我想要这样做的原因是因为当我有了这个整数变量后,我将希望将其添加到另一个整数变量中。
英文:
I have a text file (test.txt) :
Bob, 12, 15, 20
Ruth, 45, 212, 452
With Java, I want to extract only the last element of each line (each element being separated by a coma).
For now on, I wrote this code :
br = new BufferedReader(new FileReader("test.txt"));
while ((line = br.readLine()) != null) {
String[] facture = line.split(",");
int fquantite = Integer.parseInt(facture[3]);
System.out.println("Amount=" + fquantite);
But it gives me an error. The thing is that I get how to get the number (for exemple, I can write :
System.out.println("Amount=" + facture[3]);
And it works, but for some reason, I can't get to convert it to a int. The reason I want to do that is because when I'll have this int variable, I'll want to add it to another int variable.
答案1
得分: 1
使用逗号拆分,但您的输入还包含空格。使用 trim
去除它们:Integer.parseInt(facture[3].trim())
。
英文:
You split by comma, but your input also contains spaces. Use trim
to remove them: Integer.parseInt(facture[3].trim())
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论