【问题标题】:How do you create a logic loop for reading and summing data from a file?如何创建一个逻辑循环来读取和汇总文件中的数据?
【发布时间】:2017-07-29 15:22:14
【问题描述】:

我正在处理一项 Java 家庭作业,该作业需要从提供的文本文件中读取数据,处理数据以将其合并为各个状态的数据,然后将该数据放入输出文件中。我不知道如何对数据求和(我仍在处理部分伪代码,所以我什至没有尝试编译和解决编译器错误的地步)。

传入文件中的数据样本是:

01 00190 雪花石膏市学区 31754 6475 733 USSD13.txt 24NOV2014
01 00005 阿尔贝维尔市学区 21522 4010 1563 USSD13.txt 24NOV2014
01 00030 亚历山大市学区 17292 2719 1158 USSD13.txt 24NOV2014
01 00060 安达卢西亚市学区 9044 1512 471 USSD13.txt 24NOV2014
01 00090 安尼斯顿市学区 22759 3304 1122 USSD13.txt 24NOV2014
06 21060 拉森联合高中区 25961 1155 141 USSD13.txt 24NOV2014
06 21090 Lassen View Union 小学区 2805 321 68 USSD13.txt 24NOV2014
06 21150 拉顿联合联合学区 3824 818 263 USSD13.txt 24NOV2014

我可以创建一个 BufferedReader 来读取文件,并指向 readLine 的方向来解析我想要的行的各个元素。但是我不知道如何总结各个州的列,当一个州的数据结束时停止,当另一个州的数据开始时重新开始。到目前为止,这是我所拥有的:

import java.io.*;

public class ManipulateData
{
    public static void main (String [] args) throws IOException
    {
        // Decalre variables that will be used multiple times
        int i = 0;  // i will be used as a counter

        // Ensure a file is called from the terminal and an output file 
        // is specified
        if (args.length != 2)
        {
            System.out.print("Expected command line entry is: ");
            System.out.print("java ManipulateData inputFile outputFile");
            return;
        }

        // Open the input file
        try
        {
            BufferedReader fileIn = new BufferedReader(new FileReader(args[0]));
        }
        catch(IOException exception)
        {
            System.out.println("I/O Error: " + exception.getMessage());
        }

        // Read the data from the file
        // First, get the number of lines in the file
        int lines = 0;
        while (fin.readLine() != null) lines++;

        int totalLines = lines
        String [] fileLines = new String [totalLines]; // May not need this

        // Read the lines from the file into Strings and store Strings in arrays
        for (i = 0; i < totalLines; i++);
        {
            String lineOfData = BufferedReader.readLine();
            // pull individual data points from lineOfData
            int state = Integer.parseInt(lineOfData.substring(0,1));
            int population = Integer.parseInt(lineOfData.substring(82,89));
            int childPopulation = Interger.parseInt(lineOfData.substring(91,98));
            int childPovertyPopulation = Integer.parseInt(lineOfData.substring(100-107));
            // Sum data for individual state
            stateNew = state;

        // Second, get the number of states in the file
        //not sure how to find number of states
        int numStates = 0;

        // Create arrays to hold data parsed from the file
        // int [] data = new int [lines][lines][lines][lines];
        int [] states = new int [numStates]; 
        int [] pop = new int [lines];
        int [] childPop = new int [lines];
        int [] childPovPop = new int [lines];

        try
        {
            do
            {
            ReadLine for next line

            Check if State = character positions 1-2

            a.  If true:

                1.  sumPop = sumPop + pop[i]
                2.  sumChildPop = sumChildPop + childPop[i]
                3.  sumChildPovPop = sumChildPovPop + childPovPop[i]

            b.  If false:

                1.  Set state1Pop = sumPop
                2.  Set state1ChildPop = sumChildPop
                3.  Set state1ChildPovPop = sumChildPovPop
                4.  Set state1PercentChildPovPop = sumChildPovPop / sumChildPop
                5.  Set all sum values back to 0
                6.  Start loop again for next state   
            }
            while (n != -1);
        }
        catch(IOException exception)
        {
            System.out.println("Error reading file.");
        }

        // Close the original file
        try
        {
            fin.close();
        }
        catch (IOException iOException)
        {
            System.out.println("Error closing file.");
        }

        // Write the output file
        try
        {
            BufferedWriter fileOut = new BufferedWriter(new FileWriter(args[1]));
            fileOut.write("State   Population   Child Population Child Poverty Population  % Child Poverty");
            fileOut.write("-----   ----------   ---------------- ------------------------  ---------------");
            for (i = 0, i < numStates, i++);
            fileOut.write("   " + state + "    " + popSum + "          " + childPopSum + "             " + childPovPopSum + "

    }
}

所以,为了避免问题在完全缺乏理解的情况下迷失方向,我如何循环访问传入文件中的 3000 多行代码,以确保我只将状态 01 的数据添加到状态 01项目然后重新开始,只将状态 02 数据添加在一起,等等?

【问题讨论】:

  • 创建一个普通的旧 Java 对象/类来表示单个状态及其包含的数据,创建一个集合(ArrayList&lt;MyState&gt; 可以很好地工作),然后在循环中将 MyStates 添加到您的集合中如果集合已经有一个 MyState 对象,则更新一个。
  • 看来,大家都喜欢去ArrayLists。但似乎与家庭作业的情况一样,它们是不允许的:“程序不应使用任何 Java 集合(ArrayList、Map、Vector 等),除了标准 Java 数组。集合将在后面的模块中介绍。”
  • 它们非常灵活,但如果您不允许使用它们,那就不要使用它们。您被困在使用数组中,但又是一个 POJO(普通旧 Java 对象)数组,它是一个保存单个状态信息的类。您必须将数组声明为足够大以容纳您可能找到的所有状态,并且您需要在读取数据的循环之前声明您的数组,但是否则技术大体相同。
  • 我遇到的一个问题是想出一种方法来查看有多少个状态。从 1 到 50 的数据不太好;它有间隙并且数字超过 50。我需要一种方法来比较 state[i] 和 state[i+1] 并在它们相同时对数据求和,或者保存最后一个总和并重新开始如果它们不同,则为零。我想不出办法。
  • 您可以创建一个至少与最大“状态数”一样大或更大的数组,或者您可以创建一个至少与存在的最大状态数一样大或更大的数组,然后不要使用状态编号作为数组的索引,而是将其设置为 State 类的字段,这取决于您如何执行此操作。使用任何一种技术都可以轻松地遍历数组以查看状态是否存在。但首先,您需要创建包含州信息的类。

标签: java loops logic


【解决方案1】:

我花了几个小时和一个朋友一起解决这个问题。我无法解决的问题是如何捕捉数据何时从一种状态变为另一种状态。那条路是行不通的。相反,使用状态代码作为索引,即状态 01 将是索引 0,状态 02 将是索引 1,等等,并且该状态的 readLine 中的所有数据都将与正确的数组索引相关联。

  // Creates a two-dimensional array.  First dimension will be for the state value
            int[][] dataPerState = new int[56][3];
            for (int k = 0; k < 56; ++k) {
                dataPerState[k][0] = 0;
                dataPerState[k][1] = 0;
                dataPerState[k][2] = 0;
            }

            try {
                // Open the input file
                BufferedReader fileIn = new BufferedReader(new FileReader(args[0]));

                // Read data from the input file
                // First, get the number of lines in the file
                int totalLines = Integer.parseInt(args[2]);

                // Read the lines from the file into Strings and store Strings in arrays
                for (int i = 0; i < totalLines; i++)
                {
                    String lineOfData = fileIn.readLine();

                    // Pull individual data points from lineOfData
                    int state = Integer.parseInt(lineOfData.substring(0, 2).trim());
                    int population = Integer.parseInt(lineOfData.substring(82, 90).trim());
                    int childPopulation = Integer.parseInt(lineOfData.substring(91, 99).trim());
                    int childPovertyPopulation = Integer.parseInt(lineOfData.substring(100, 108).trim());

                    // Don't need to check to make sure state didn't change.
                    // Just use the state value as the index value for the 
                    // first dimension of the 2D array.  The summing follows
                    // naturally afterwards.
                    dataPerState[state - 1][0] += population;
                    dataPerState[state - 1][1] += childPopulation;
                    dataPerState[state - 1][2] += childPovertyPopulation;
                }

                // Close the input file
                fileIn.close();
            } catch (IOException exception) {
                System.out.println("I/O Error: " + exception.getMessage());
            }

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2021-07-09
    • 2023-01-24
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多