从txt文件中仅读取整数并将每个发现的值相加 [英] Reading only the integers from a txt file and adding the value up for each found
问题描述
我正在尝试读取一个包含整数字符串的txt文件.我希望能够仅从此文件中获取整数并将每个值相加以创建总计.我设法很好地读取了文件,并且能够识别出整数和非整数.我将如何将整数加在一起?
I am trying to read a txt file that contains strings with integers. I would like to be able to get just the integers from this file and add the value each to create a total. I have managed to read the file fine and have been able to identify the ints and non. How would I go about adding the integers together?
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
推荐答案
您必须原谅我,这种方法行不通.您需要做的是一次读取一行,然后将行按每个空格分开,以获取一组单词.从那里您可以识别整数并存储值.
You'll have to excuse me, that method will not work. What you need to do is read one line at a time, then split the line by each space, to get an array of words. From there you can identify integers and store the value.
final static String filename = "FILENAME.txt";
public static void main(String[] args) {
Scanner scan = null;
File f = new File(filename);
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
int total = 0;
boolean foundInts = false; //flag to see if there are any integers
while (scan.hasNextLine()) { //Note change
String currentLine = scan.nextLine();
//split into words
String words[] = currentLine.split(" ");
//For each word in the line
for(String str : words) {
try {
int num = Integer.parseInt(str);
total += num;
foundInts = true;
System.out.println("Found: " + num);
}catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
}
} //end while
if(!foundInts)
System.out.println("No numbers found.");
else
System.out.println("Total: " + total);
// close the scanner
scan.close();
}
这篇关于从txt文件中仅读取整数并将每个发现的值相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!