2016-08-16 10 views
0

をint 2d配列に格納します。roomLayout = new int [numberOfRooms // = 5] [Arr.length];2d配列のjavaにtxtファイルからデータを格納するには?

これは私が今

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 [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の使用について異議がない場合、あなたはこれを簡単なアプローチ取ることができます: `roomLayout`割り当てが可能

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; 
} 
関連する問題