有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从文本文件中读取数字字符串并将它们相加

我有一本书。txt调用输出。这是该文件的内容

Image of notepad document

我想从每个数字中读出最后的数字(第四位)
然后把它们加在一起得到一个总数。我主要想知道如何将文本转换成一些有用的变量

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. ");
    }
}

}


共 (3) 个答案

  1. # 1 楼答案

    使用java 8,下面的方法将读取文件,过滤掉,只对匹配“字符串编号”的行进行操作,然后对最终的数字列求和

    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]))将拆分从“”上的筛选器接收的任何行,然后获取最终字符串的长值

    .reduce((p, c) -> p + c)将对从地图接收到的每个数字求和

  2. # 2 楼答案

    Steps the algorithm (code) follows:

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

    2)Initialise将存储sumcounter(我使用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 filenumber of accounts (i.e. number of lines)sum

    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.

  3. # 3 楼答案

    这是一个非常模糊的问题,所以这是一个非常模糊的回答。使用“for”循环在。txt文件逐行存储到数组中