[英]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.