【发布时间】:2011-04-27 02:05:45
【问题描述】:
我有一个从字符串构建的多维数组,最初创建的大小为 [50][50],它太大了,现在数组中充满了空值,我目前正在尝试删除这些空值,我已设法将数组的大小调整为 [requiredSize][50] 但无法进一步缩小它,有人可以帮我解决这个问题吗?我已经在互联网上搜索过这样的答案,但找不到。
这也是我的完整代码(我意识到我的代码中可能有一些非常不干净的部分,我还没有清理任何东西)
import java.io.*;
import java.util.*;
public class FooBar
{
public static String[][] loadCSV()
{
FileInputStream inStream;
InputStreamReader inFile;
BufferedReader br;
String line;
int lineNum, tokNum, ii, jj;
String [][] CSV, TempArray, TempArray2;
lineNum = tokNum = ii = jj = 0;
TempArray = new String[50][50];
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the file path of the CSV");
String fileName = in.readLine();
inStream = new FileInputStream(fileName);
inFile = new InputStreamReader(inStream);
br = new BufferedReader(inFile);
StringTokenizer tok,tok2;
lineNum = 0;
line = br.readLine();
tokNum = 0;
tok = new StringTokenizer(line, ",");
while( tok.hasMoreTokens())
{
TempArray[tokNum][0] = tok.nextToken();
tokNum++;
}
tokNum = 0;
lineNum++;
while( line != null)
{
line = br.readLine();
if (line != null)
{
tokNum = 0;
tok2 = new StringTokenizer(line, ",");
while(tok2.hasMoreTokens())
{
TempArray[tokNum][lineNum] = tok2.nextToken();
tokNum++;
}
}
lineNum++;
}
}
catch(IOException e)
{
System.out.println("Error file may not be accessible, check the path and try again");
}
CSV = new String[tokNum][50];
for (ii=0; ii<tokNum-1 ;ii++)
{
System.arraycopy(TempArray[ii],0,CSV[ii],0,TempArray[ii].length);
}
return CSV;
}
public static void main (String args[])
{
String [][] CSV;
CSV = loadCSV();
System.out.println(Arrays.deepToString(CSV));
}
}
CSV 文件如下所示
Height,Weight,Age,TER,Salary
163.9,46.8,37,72.6,53010.68
191.3,91.4,32,92.2,66068.51
166.5,51.1,27,77.6,42724.34
156.3,55.7,21,81.1,50531.91
显然它可以采用任何大小,但这只是一个示例文件。
我只需要调整数组的大小,使其不包含任何空值。
我也明白在这里列出一个列表会是一个更好的选择,但由于外部限制,这是不可能的。只能是多维数组。
【问题讨论】:
-
如果不能选择使用列表,您可以拥有自己的动态数组实现,在需要时扩展数组并复制新构造的数组中的旧值。或者您可以读取该文件两次。首先找到行数和列数,然后在第二次读取定义数组时,填写数组中的值
标签: java resize multidimensional-array arrays