![](/img/trans.png)
[英]Read a String from a txt file and store it into a char array in java
[英]Read .txt file and store in 2-D char array java
我有點卡住。 我如何使它工作或有更好的方法? 請提供代碼示例。
public char[][] charmap = new char[SomeInts.amount][SomeInts.amount];
public void loadMap() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("map1.txt"));
String line = in.readLine();
while (line != null){
int y = 0;
for (int x = 0; x < line.length(); x++){
//Error
charmap[x][y] = line[x];
//
}
y++;
}
}
語法line[x]
保留用於數組。 字符串不是數組。 您可以使用String#charAt
方法並編寫:
charmap[x][y] = line.charAt(x);
使用String.charAt(int)從字符串中獲取字符。
嘗試這個。
char[][] mapdata = new char[SomeInts.amount][SomeInts.amount];
public void loadMap() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("map1.txt"));
String line = in.readLine();
ArrayList<String> lines = new ArrayList<String>();
// Load all the lines
while (line != null){
lines.add(line);
}
// Parse the data
for (int i = 0; i < lines.size(); i++) {
for (int j = 0; j < lines.get(i).length(); j++) {
mapdata[j][i] = lines.get(i).charAt(j);
}
}
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.