从字符串文件中提取一个值并使用 Java 将其转换为 int
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]);
它可以工作,但出于某种原因,我无法将它转换为 int。我想这样做的原因是因为当我拥有这个 int 变量时,我想将它添加到另一个 int 变量。
您用逗号分隔,但您的输入也包含空格。使用 trim
删除它们:Integer.parseInt(facture[3].trim())
.
我有一个文本文件 (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]);
它可以工作,但出于某种原因,我无法将它转换为 int。我想这样做的原因是因为当我拥有这个 int 变量时,我想将它添加到另一个 int 变量。
您用逗号分隔,但您的输入也包含空格。使用 trim
删除它们:Integer.parseInt(facture[3].trim())
.