這是我第一次使用陣列,尤其是 Java 中的檔案,我遇到了如何將資料從檔案輸出到二維陣列的問題。
所以在這里我嘗試使用這些資料為游戲構建地圖并將其保存為二維陣列。怎么做?
我在檔案中的資料:
8
2 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 0 0 0 0 0 0 0
1 0 1 0 0 1 0 1
1 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
我得到的錯誤:
檔案檔案 運算式的型別必須是陣列型別,但它決議為檔案
File file = new File("map1.txt");
private final char[] allowed = {'0', '1', '2'};
public List<Position> pPos = new ArrayList<>();
Map(Scanner scan) throws InvalidMapException {
List<String> strings = new ArrayList<>();
int size = 8;
boolean isValid = false;
for(int i = 0; i < size; i ) {
strings.add(size);
for(char ch : allowed) {
if(strings.get(strings.size() - 1).charAt(0) == ch) {
isValid = true;
}
}
if(!isValid) {
throw new InvalidMapException("Illegal character");
}
}
isValid = false;
if(strings.size() != size) {
throw new InvalidMapException("Map error");
}
isValid = false;
int chCounter = 0;
int xCounter = 0;
int yCounter = 0;
for(String string : strings) {
for(char ch : strings.toCharArray()) {
if(ch == ' ') {
continue;
}
if(ch == '2') {
pPos.add(new Position(xCounter, yCounter));
}
chCounter ;
for(char aCh: allowed) {
if(ch == allowed) {
isValid = true;
break;
}
}
if(!isValid) {
throw new InvalidMapException("character error");
}
isValid = false;
chCounter ;
}
if(chCounter != strings.size()) {
System.out.println(chCounter " " strings.size());
throw new InvalidMapException("size error");
}
chCounter = 0;
yCounter ;
xCounter = 0;
}
file = new char[strings.size()][strings.size()];
int i = 0; int j = 0;
for(String string : strings) {
for(char ch : string.toCharArray()) {
if(ch != ' ') {
file[i][j] = ch; //Here is the error.
j ;
}
}
}
}
uj5u.com熱心網友回復:
盡量保持解決方案簡單易讀,請試試這個 -
File file = new File("map1.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = reader.readLine();
int size = Integer.parseInt(line);
int[][] array = new int[size][size];
int i = 0;
while ((line = reader.readLine()) != null) {
int j = 0;
String[] lineValues = line.split(" ");
for (String value : lineValues) {
array[i][j] = Integer.parseInt(value);
j ;
}
i ;
}
}
uj5u.com熱心網友回復:
你這樣做非常復雜。
讀取檔案的所有行:
List<String> lines = new ArrayList<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
}
}
然后用 String.split(" ") 分割行。您將得到一個每行包含所有數字的陣列。將它們存盤在串列中。
之后,您可以從專案中創建一個二維陣列。
uj5u.com熱心網友回復:
嗨,變數檔案的型別是 java.io.File。您正在嘗試為其分配一個 char 陣列,這是不可能的。你需要使用這樣的東西
char[][] charArray = new char[strings.size()][strings.size()];
無論如何,我建議您遵循 David 建議的方法,而不是您發布的復雜代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/497974.html
