gpt4 book ai didi

java - 仅从 txt 文件中读取整数并将每个找到的值相加

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:04 25 4
gpt4 key购买 nike

我正在尝试读取包含整数字符串的 txt 文件。我希望能够从该文件中获取整数并将每个值相加以创建总计。我已经成功地读取了该文件,并且能够识别整数和非整数。我该如何将整数相加呢?

public void goalCount() throws FileNotFoundException {

int goals=0;
double total=0;

try {
Scanner scan = new Scanner(new File("validtest.txt.txt"));

// find the next int token and print it
// loop for the whole scanner
while (scan.hasNext()) {

// if the next is a int, print found and the int
if (scan.hasNextInt()) {
System.out.println("Found :" + scan.nextInt());
//goals = scan.nextInt();
//total+= goals;
}
// if no int is found, print "Not Found:" and the token
System.out.println("Not Found :" + scan.next());
}

// close the scanner
scan.close();

} catch(Exception e) {

}
System.out.println("Total Goals:"+total); //error handling
}

txt 文件示例

Leeds United : Liverpool : 1 : 2
Chelsea : Manchester City : 1 : 1
Aston Villa : Middlesbrough : 3 : 1
Tottenham Hotspur : Stoke City : 0 : 0

最佳答案

您可以将它们添加到列表中,而不是打印出整数。

List<Integer> goals = new ArrayList<Integer>();
goals.add(scan.nextInt());

然后将它们相加!

或者,如果您不需要单独访问它们,您可以简单地,

total = total + scan.nextInt(); //OR total += scan.nextInt();

在您的 if(scan.hasNextInt()) block 中

关于java - 仅从 txt 文件中读取整数并将每个找到的值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27405296/

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