java从文本文件中读取数字字符串并将它们相加
我有一本书。txt调用输出。这是该文件的内容
我想从每个数字中读出最后的数字(第四位)
然后把它们加在一起得到一个总数。我主要想知道如何将文本转换成一些有用的变量
import java.io .*;
import java.util.*;
public class PrintTotalPointsHeld
{
private int count;
private String id;
private File inFile;
private Scanner input;
private String name;
private File outFile;
private PrintWriter output;
private int total;
public PrintTotalPointsHeld (String name, String id, String inFilename, String outFilename) throws Exception, IOException
{
}
public void processFiles() throws Exception, IOException
{
// Stores every word as a variable so we can do our calculations later
try(BufferedReader br = new BufferedReader(new FileReader(inFile))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String points = sb.toString();
}
output.println("There are " + count + " accounts that together hold " + total + " points. ");
}
}
}
# 1 楼答案
使用java 8,下面的方法将读取文件,过滤掉,只对匹配“字符串编号”的行进行操作,然后对最终的数字列求和
.filter(s -> s.matches("^\\w+\\s\\w+\\s\\d+\\s\\d+$"))
意味着只有以单词开头,然后有空格,然后是数字,然后是数字,最后是行尾的行才会被作用.map(s -> Long.valueOf(s.split(" ")[3]))
将拆分从“”上的筛选器接收的任何行,然后获取最终字符串的长值.reduce((p, c) -> p + c)
将对从地图接收到的每个数字求和# 2 楼答案
1)
Open
包含您想要阅读的内容的file
(使用BufferedReader
)2)
Initialise
将存储sum
的counter
(我使用long
,因为你的sum
可以获得extremely big
,而integer
可能无法获得hold such big numbers
)3)}每一行使用}开始),其中包含}
Read line by line the file
(使用String line = myReader.readLine();
获取下一行,确保有下一行使用while(line != null){
{space
作为分隔符,保留每个数组的4th
元素(parts[3]
,因为数组从^number you want to add
,并且adding
将该数字保留到^4)
Print
当有no lines left to read in the file
时number of accounts (i.e. number of lines)
和sum
输出:
There are 3 accounts that together hold 2558543 points.
# 3 楼答案
这是一个非常模糊的问题,所以这是一个非常模糊的回答。使用“for”循环在。txt文件逐行存储到数组中