从文本文件中读取一串数字并将它们相加
Read string of numbers from text file and add them together
我有一个名为 output.txt 的 .txt,这是该文件的内容
我想从每个(第 4 个位置)读取最后一个数字
并将它们加在一起得到总数。主要是想知道怎么把文字变成一些可用的变量。
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. ");
}
}
}
使用 java 8 以下方法将读取文件,过滤掉并仅在匹配 "String String Number Number" 的行上工作,然后对最终数字列求和
public Optional<Long> sumFinalColumnOfFile(String filePath) throws IOException {
Path path = FileSystems.getDefault().getPath(filePath);
return Files.lines(path)
.filter(s -> s.matches("^\w+\s\w+\s\d+\s\d+$"))
.map(s -> Long.valueOf(s.split(" ")[3]))
.reduce((p, c) -> p + c);
}
.filter(s -> s.matches("^\w+\s\w+\s\d+\s\d+$"))
表示只有以单词开头的行,然后是space,然后是数字,然后是数字,然后是行尾
.map(s -> Long.valueOf(s.split(" ")[3]))
将拆分它从 " " 上的过滤器接收到的任何行,然后获取最终字符串的 Long 值
.reduce((p, c) -> p + c)
将从地图接收到的每个数字求和
Steps the algorithm (code) follows:
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){
splitting
每行使用 space
作为分隔符,保留每个数组的 4th
元素(parts[3]
,因为数组从 0
开始),其中包含 number you want to add
,并且 adding
这个数字到 previous sum
4) Print
number of accounts (i.e. number of lines)
和 sum
当有 no lines left to read in the file
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
long cnt = 0;
long numberOfLines = 0;
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String line = myReader.readLine();
while(line != null){
numberOfLines++;
String[] parts = line.split(" ");
cnt = cnt + Integer.parseInt(parts[3]);
line = myReader.readLine();
}
System.out.println("There are " + numberOfLines + " accounts that together hold " + cnt + " points.");
}
}
输出:There are 3 accounts that together hold 2558543 points.
这是一个非常模糊的问题,所以这是一个非常模糊的回答。使用 "for" 循环逐行遍历 .txt 文件并存储到数组中
只需拆分行并获取具有适当索引的第四个元素:
FileReader file = new FileReader(new File("test.txt"));
BufferedReader reader = new BufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line.split(" ")[3]);
}
如果您确定要加起来的数字总是在第 4 个位置;使用 String class:
中的 split() 方法
BufferedReader br = new BufferedReader(new FileReader(inFile));
String process = br.readLine();
int total = 0;
while(process != null){
String[] columns = process.split(" "); //This array will contain all columns from a single row starting index 0
total = total + Integer.parseInt(columns[3]);
process = br.readLine();
}
计算总数后,才将最后一行写入文件。
我有一个名为 output.txt 的 .txt,这是该文件的内容
我想从每个(第 4 个位置)读取最后一个数字
并将它们加在一起得到总数。主要是想知道怎么把文字变成一些可用的变量。
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. ");
}
}
}
使用 java 8 以下方法将读取文件,过滤掉并仅在匹配 "String String Number Number" 的行上工作,然后对最终数字列求和
public Optional<Long> sumFinalColumnOfFile(String filePath) throws IOException {
Path path = FileSystems.getDefault().getPath(filePath);
return Files.lines(path)
.filter(s -> s.matches("^\w+\s\w+\s\d+\s\d+$"))
.map(s -> Long.valueOf(s.split(" ")[3]))
.reduce((p, c) -> p + c);
}
.filter(s -> s.matches("^\w+\s\w+\s\d+\s\d+$"))
表示只有以单词开头的行,然后是space,然后是数字,然后是数字,然后是行尾
.map(s -> Long.valueOf(s.split(" ")[3]))
将拆分它从 " " 上的过滤器接收到的任何行,然后获取最终字符串的 Long 值
.reduce((p, c) -> p + c)
将从地图接收到的每个数字求和
Steps the algorithm (code) follows:
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){
splitting
每行使用 space
作为分隔符,保留每个数组的 4th
元素(parts[3]
,因为数组从 0
开始),其中包含 number you want to add
,并且 adding
这个数字到 previous sum
4) Print
number of accounts (i.e. number of lines)
和 sum
当有 no lines left to read in the file
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
long cnt = 0;
long numberOfLines = 0;
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String line = myReader.readLine();
while(line != null){
numberOfLines++;
String[] parts = line.split(" ");
cnt = cnt + Integer.parseInt(parts[3]);
line = myReader.readLine();
}
System.out.println("There are " + numberOfLines + " accounts that together hold " + cnt + " points.");
}
}
输出:There are 3 accounts that together hold 2558543 points.
这是一个非常模糊的问题,所以这是一个非常模糊的回答。使用 "for" 循环逐行遍历 .txt 文件并存储到数组中
只需拆分行并获取具有适当索引的第四个元素:
FileReader file = new FileReader(new File("test.txt"));
BufferedReader reader = new BufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line.split(" ")[3]);
}
如果您确定要加起来的数字总是在第 4 个位置;使用 String class:
中的 split() 方法BufferedReader br = new BufferedReader(new FileReader(inFile));
String process = br.readLine();
int total = 0;
while(process != null){
String[] columns = process.split(" "); //This array will contain all columns from a single row starting index 0
total = total + Integer.parseInt(columns[3]);
process = br.readLine();
}
计算总数后,才将最后一行写入文件。