简体   繁体   English

Java中2D数组的实际大小(2D数组的填充区域)

[英]The real size of a 2D Array, (Filled area of 2D array), in Java

I'm having problem with my homework assignment, and hoping to find some help. 我在做作业时遇到问题,希望能找到帮助。

I have to read a text file into a 2D int array. 我必须将文本文件读入2D int数组。 The width of the 2D array is fixed at 5 and will never change. 2D数组的宽度固定为5,并且永远不会改变。 However, the height of the array may change depend on the length of the text file. 但是,数组的高度可能会根据文本文件的长度而变化。

I have to begin with a 40x5 array; 我必须从40x5数组开始; any file over 40 lines will not acceptable, but less than 40 will be OK. 任何超过40行的文件都是不可接受的,但是少于40行的文件是可以的。 So, I may get only X rows of my array be filled (X <= 40). 因此,我可能只填充数组的X行(X <= 40)。

I have to calculate the average of each column, so I need to how many elements in a column; 我必须计算每列的平均值,因此我需要计算一列中有多少个元素。 Is there any way to get that? 有什么办法做到这一点? Or can I change the size of my original array (with all the data in it) to Xx5 after I know what X is? 或者在知道X是什么之后,是否可以将原始数组(包含所有数据)的大小更改为Xx5?

The sample input file: 示例输入文件:

034 080 055 078 045
060 100 056 078 078
070 010 066 078 056
034 009 077 078 020
045 040 088 078 055

output should be: 输出应为:

48.6 47.8 68.4 78.0 50.8

I wouldn't recommend using a plain array for a dynamically expanding matrix like this. 我不建议对这样的动态扩展矩阵使用普通数组。 I recommend reading up on the List & ArrayList documentation for a good implementation. 我建议阅读List&ArrayList文档以获得良好的实现。

From the Java doc: [ArrayList is a] resizable-array implementation of the List interface. 从Java文档开始: [ArrayList is a] resizable-array implementation of the List interface.

In effect, this is Java's solution to the constantly-defined array limitation of the C days. 实际上,这是Java对C天不断定义的数组限制的解决方案。

What you need to do is calculate a sum of each separate column (easy; you don't need to keep the whole state, just the running total for each column) plus a count of the number of rows. 您需要做的是计算每个单独列的总和(简单;您不需要保留整个状态,只需保持每一列的运行总数)加上行数即可。 Given that, computing the average of each column should then be easy. 鉴于此,计算每一列的平均值应该很容易。 You can do all this in a single pass reading just one row at a time, and your solution should be able to handle files of any length. 您只需一次读取一次即可完成所有这些操作,并且您的解决方案应该能够处理任何长度的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM