【发布时间】:2014-01-23 05:32:54
【问题描述】:
这是我发现有助于读取二维数组的一些代码,但我遇到的问题是这仅在读取结构如下的数字列表时才有效:
73
56
30
75
80
ect..
我想要的是能够读取结构如下的多行:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
我只想将每一行作为一个数组导入,同时在文本文件中像数组一样构建它们。 我读过的所有内容都说要使用 scan.usedelimiter(",");但是在我尝试使用它的任何地方,程序都会直接抛出回复“错误转换数字”的问题。如果有人可以提供帮助,我将不胜感激。我还看到了一些关于对缓冲阅读器使用 split 的信息,但我不知道哪个会更好/为什么/如何使用。
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
【问题讨论】:
-
你为什么不把整个东西读成一个字符串。在","s上拆分字符串,然后将其转换为二维数组?
-
在你的 catch 语句中而不是仅仅打印出“错误转换数字”使用 e.printStackTrace()。或 System.out.println(e)。这样你就可以真正看到错误是什么。
-
你的问题解决了吗???
标签: java arrays split 2d delimiter