[英]How can I read a String from a file split it into characters and put it in to a 2D array?
[英]How to read a file with scanner, then put into a 2D array of characters
我有一个文本文件,该文件基本上具有一堆字符的图片。
我正在使用scanner.nextLine并将其保存到字符串,然后使用该字符串的charAt(index)来获取每个位置的单个字符并将其保存到matrix [I] [j]。 当我尝试使用嵌套的for循环打印出图片时,它看起来与文本文件看起来完全不同。
String string;
Scanner pic = new Scanner(new File("/Users/yoyoma/eclipse-workspace/Picture/resources/pics/" + filename));
int row = pic.nextInt();
int col = pic.nextInt();
char[][] picture = new char[row][col];
for(int i = 0; i < row; i++) {
if(pic.hasNextLine()) {
string = pic.nextLine();
for(int j = 0; j < col; j++) {
for(int a = 0; a < string.length(); a++) {
picture[i][j] = string.charAt(a);
}
}
}
}
for (int z = 0; z < row; z++) {
for (int x = 0; x < col; x++) {
System.out.print(pic[z][x]);
}
System.out.println();
}
我希望图片看起来像在文本文件中那样,相反,我得到了很多'ol混杂的字符,它们以错误的顺序排列,甚至丢失了一些。
//This is what the text file looks like:
10 10
## #######
#
# #
# ######
# # #
#G # #
# # #
# L # #
# #
######## #
//Here is my output:
##########
##########
##########
##########
##########
##########
##########
您遇到的问题与您的读者有关。 特别
for(int j = 0; j < col; j++) {
for(int a = 0; a < string.length(); a++) {
picture[i][j] = string.charAt(a);
}
}
基本上,您将读取该行10次,并将每个列设置为j的每个循环结束时该行的最后一个字符。
您需要将其修改为:
for(int j = 0; j < col; j++) {
picture[i][j] = string.charAt(j);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.