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

huangapple go评论77阅读模式
英文:

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()).

huangapple
  • 本文由 发表于 2020年7月23日 00:53:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63039366.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定