简体   繁体   English

从字符串文件中提取一个值并使用 Java 将其转换为 int

[英]Extract a value from a string file and converting it to int with Java

I have a text file (test.txt):我有一个文本文件(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).使用 Java,我只想提取每行的最后一个元素(每个元素用逗号分隔)。

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]);问题是我知道如何获取数字(例如,我可以写: System.out.println("Amount=" + facture[3]);

And it works, but for some reason, I can't get to convert it to a int.它可以工作,但由于某种原因,我无法将其转换为 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.我想这样做的原因是当我拥有这个 int 变量时,我想将它添加到另一个 int 变量中。

You split by comma, but your input also contains spaces.您用逗号分隔,但您的输入也包含空格。 Use trim to remove them: Integer.parseInt(facture[3].trim()) .使用trim删除它们: Integer.parseInt(facture[3].trim())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM