并将其存储到int 2d数组roomLayout = new int[numberOfRooms//=5][Arr.length];
这是我现在得到的
str = gamemap.readLine();
String[] strArr = str.split(",");
System.out.println(str);
roomLayout = new int[numberOfRooms][str.length];
for (String number : strArr)
{
int strToInt = Integer.parseInt(number);
System.out.print(number);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
// all lines in file
ArrayList<String> lines = new ArrayList();
BufferedReader in = new BufferedReader(new FileReader("map.txt"));
String line;
// read lines in file
while ((line = in.readLine())!=null){
lines.add(line);
}
in.close();
// create new 2d array
int[][] map = new int[lines.size()][];
// loop through array for each line
for (int q = 0; q < map.length; q++){
// get the rooms by separating by ","
String[] rooms = lines.get(q).split(",");
// size 2d array
map[q] = new int[rooms.length];
// loop through and add to array's second dimension
for (int w = 0; w < rooms.length; w++){
map[q][w] = Integer.parseInt(rooms[w]);
}
System.out.println(Arrays.toString(map[q]));
}
}
输出如下:
[2]
[1, 3, 5]
[2, 5]
[3, 4, 2]
[5]
您可以继续使用以下方法。
String yourString="2n1,3,5n2,5n3,4,2n5"; //Added newline characters for each newline
String lines[]=yourString.split("n");
int roomLayout[][]=new int[lines.length][];
// for each line, split them and store them in your 2d array
for(int i=0;i<lines.length;i++){
String parts[]=lines[i].split(",");
int[] numbers=new int[parts.length];
for(int j=0;j<parts.length;j++){
numbers[j]=Integer.parseInt(parts[j]);
}
// assign your row as a row in the roomLayout.
roomLayout[i]=numbers;
}
// Whenever you access the array, that is i'th room (indexed from 0)
// access allowed rooms as
for(int x=0;x<rooLayout[i].length;x++){
System.out.println(roomLayout[i][x]);
}
否则你可以选择ArrayLists
,这在你的情况下是一个很好的选择。
如果您对使用Java 8没有异议,您可以采用以下更简单的方法:
public static int[][] readRoomLayout(String fileName) throws IOException {
int[][] roomLayout = null;
Path filePath = Paths.get(fileName);
Function<String, int[]> toIntArrayFunction = string -> {
String[] splitted = string.split(",");
return Arrays.stream(splitted).mapToInt(Integer::parseInt).toArray();
};
List<int[]> rooms = Files.lines(filePath).map(toIntArrayFunction)
.collect(Collectors.toList());
roomLayout = rooms.toArray(new int[rooms.size()][]);
return roomLayout;
}