gpt4 book ai didi

java - 从文本文件中检索某些变量

转载 作者:行者123 更新时间:2023-12-01 18:39:02 24 4
gpt4 key购买 nike

我正在尝试编写一个程序的一部分,该程序读取一个文本文件,然后从文件中的每一行检索一个整数并将它们加在一起。我已经设法检索该整数,但是每一行都包含多个整数,导致我无意中选取了我不需要的其他整数。是否可以跳过某些整数?文本文件的格式可以在下面的链接中看到。

Text file

我试图收集的整数是上面文本文件中从左起第三个变量(3、6 和 4),但是我也选择了 60、40 和 40,因为它们是也是整数。

这是我到目前为止得到的代码。

public static double getAverageItems (String filename, int policyCount) throws IOException {

Scanner input = null;
int itemAmount = 0;

input = new Scanner(new File(filename));
while (input.hasNext()) {
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
}
}
return itemAmount;

}

最佳答案

只需添加input.nextLine():

 if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
}

根据文档:nextLine 使扫描器前进到当前行并返回跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。

另一种方法是解析每一行并获取第三列。

BufferedReader r = new BufferedReader(new FileReader(filename));
while (true) {
String line = r.readLine();
if (line==null) break;
String cols[] line.split("\\s+");
itemAmount += Integer.parseInt(cols[2]);
}
r.close();

关于java - 从文本文件中检索某些变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20690650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com