从文本文件中读取数字串并将它们一起添加

时间:2015-03-17 20:41:22

标签: java file java.util.scanner

我有一个名为output.txt的.txt,这是该文件的内容

Image of notepad document

我想从每个(第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. ");
    }
}

}

5 个答案:

答案 0 :(得分:3)

  

步骤算法(代码)如下:

1)Open file包含您要阅读的内容(使用BufferedReader

2)Initialise counter将存储sum(我使用long,因为您的sum可以获得extremely biginteger {1}}可能无法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 addadding此数字为{{1} }}

4)previous sum Printnumber 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."); } }

答案 1 :(得分:1)

如果您确定要添加的数字总是位于第4位;使用String类的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();
}

计算总数后,才将最后一行写入文件。

答案 2 :(得分:0)

使用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+$"))表示只有以单词开头的行,然后有空格,然后是数字,然后是数字,然后是行尾

.map(s -> Long.valueOf(s.split(" ")[3]))会将从过滤器收到的所有行拆分为“”,然后获取最终字符串的Long值

.reduce((p, c) -> p + c)会将从地图收到的每个号码相加

答案 3 :(得分:0)

只需拆分该行并使用适当的索引获取第四个元素:

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 :(得分:-3)

这是一个令人难以置信的模糊问题,所以这是一个非常模糊的回答。使用“for”循环逐行迭代.txt文件并存储到数组