2016-08-16 109 views
0

并将其存储到int 2d数组roomLayout = new int [numberOfRooms // = 5] [Arr.length];如何将数据从txt文件存储到2d数组java中?

这是我得到直到现在

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); 
} 
+0

'roomLayout'分配可像'roomLayout [0] [0] = 2;' –

+0

'完成你需要解释你为什么期待这样的结果 - 你的逻辑是什么。 'numberOfRooms'从哪里来? –

回答

0

你可以去用下面的方法。

String yourString="2\n1,3,5\n2,5\n3,4,2\n5"; //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,这是一个很好的选择在你的情况。

1
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] 
0

如果你不知道使用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; 
} 
相关问题