【发布时间】:2014-09-15 06:10:45
【问题描述】:
您好,我是 2D 数组的新手,在显示数组索引的内容时遇到问题。我正在从文本文件中读取值并将它们存储到二维数组中。我不确定这些物品是否正确存放。当我在填充 2D 数组的迭代过程中使用 System.println() 时,它会打印出当前显示的所有值。但是,如果我尝试填充数组并调用任何位置索引,例如 data[45][45];它只会返回一个 0。从应该存储的文本文件中获取的每个 int 值都以百万为单位。
final String FILENAME = "DATA.TXT";
int [ ][ ] data = null;
int numberOfRows = 0;
int numberOfCols = 0;
String message ="";
try {
File file = new File(FILENAME);
Scanner inputFile = new Scanner(file);
// Read the number of Rows and Columns first
numberOfRows = inputFile.nextInt();
numberOfCols = inputFile.nextInt();
//Creates the row and column amount
data = new int[numberOfRows][numberOfCols];
for(int i = 0; i < data.length; i++)
{
for(int j = 0; j < data[5].length; j++)
{
while(inputFile.hasNextInt())
{
data[i][j] = inputFile.nextInt();
//System.out.println(data[i][j]); //This works for displaying the values cuurently
}
}
}
inputFile.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Error reading data from " + FILENAME +
" Exception = " + ex.getMessage());
}
System.out.println("Data has been read - file has " + numberOfRows +
" rows and " + numberOfCols + " columns.");
//THIS or even using a loop to iterate through the 2D array that should contain
// the values does not appear and only ends up as 0 as if the values are not stored.
System.out.print(data[56][56]);
}
}
我已经看了几个小时,但我不明白这些值是否没有正确存储,或者是否有原因我无法在任何数据索引中调用该值,例如 data[45][45]或使用循环,例如
for(int n =0; n <data.length; n++)
{
for(int k = 0; k < data[0].length; k++)
{
System.out.print(data[n][k]);
}
}
如果我这样做完全错误,或者有更有效的方法可以做到这一点,请告诉我。否则一般我不知道出了什么问题。
感谢您查看我的帖子,我相信这将有助于许多新程序员进行二维数组和文件读取。
文件内容
500 1000 1052662 1025260 1064342 1045596 1093363 1063663 1014129 1070544 1005352 1046317 1059536 1009817 1049327 1012134 1047499 1026392 1056558 1098823 1060554 1028017 1046977 1022098 1018538 1077771 1082687 1025653 1056869 1076473 1097420 1080444 1063797 1014295 1083251 1037760 1026325 1003914 1034680 1069524 1029877 1075546 1047177 1061381 1080359 1035442 P>
【问题讨论】:
-
介意发布文件内容吗?
-
我发布了一些文件内容,其余的就这样继续。我认为有 20 000 条记录
-
你的循环不对。它从您的“while”中读取文件中的所有值,但在读取所有值之前,“for”循环不会增加。因此 data[i][j] = inputFile.nextInt() 总是将读取的 int 存储在 data[0][0] 中,之后存储在 data[1][0] 中,依此类推
-
对不起,我不太明白你的意思。时间有问题吗?没有它,它给了我一个 outofboundsexception
-
可能是因为 i