如何将数据从txt文件存储到2d数组java?(How to store data from txt file into 2d array java?)

编程入门 行业动态 更新时间:2024-10-25 20:27:22
如何将数据从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.

更多推荐

本文发布于:2023-07-29 05:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1312640.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何将   文件   数据   txt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!