如何将数据从txt文件存储到2d数组java?(How to store data from txt file into 2d array java?)
并将其存储到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); }and store it into an int 2d array roomLayout = new int[numberOfRooms//=5][Arr.length];
This is what i got until now
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); }最满意答案
您可以继续使用以下方法。
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 ,这是一个很好的替代方案。
You can go on with the following approach.
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]); }Otherwise you can go with ArrayLists, which is a good alternative in your situation.
更多推荐
发布评论