[英]Text file to 2D array
我正在逐行读取文本文件,现在我想将其排列为2d数组,但是我被卡住了。 这是代码:
BufferedReader bfr = new BufferedReader(new FileReader("Data.txt"));
String line;
while ((line = bfr.readLine()) != null) {
System.out.println(line);
}
bfr.close();
所以我得到了它来打印文本文件,但现在我想将其排列成二维数组。 有什么帮助吗?
java中有一个很棒的类,称为Scanner,可用于与流数据相关的许多事情。
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
您可以将其用于文件。 它将逐行读取。 在这里打印,但是将其存储在数组中就完成了!
尝试制作一个ArrayList:
ArrayList<String> bob = new ArrayList<String>();
然后,您可以简单地进行以下操作:
bob.add(line);
然后将其打印出来,您可以:
for(int x = 0; x < bob.length; x++) {
System.out.println(bob[x]);
}
那应该工作。 :)
文本到二维数组? 有趣而且很普通。 如上一个答案中所述,扫描仪可能会有用,但是您获取文本文件的方法很好。 即使扫描仪的速度性能可能会好一点(进行一些研究。
我要解决此问题的方法是在每个放置的tile(?)之间添加一个定界符。 例:
1:1:1:1:1:1:1
1:0:1:0:0:0:1
1:0:0:0:1:0:1
1:1:1:1:1:1:1
这使您可以抓取一行,然后使用String.split(String delimiter)
方法将其拆分。 正如LouisDev所说,“扫描仪”更好,所以我将使用它:
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
int y = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
y++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
因此,我们有获取线并将其存储到变量y中的方法 。 在以下方法中将使用此方法,该方法显示了一种收集字符串中所有内容并将其存储到2D数组中的方法。 实际上,这是您的问题的答案。
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
int y = 0;
int[][] map = new int[methodParsedHeight][methodParsedWidth];
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] lineSplit = line.split(":");
for(int x = 0; x < lineSplit.length; x++ {
map[y][x] = Integer.parseInt(lineSplit[x]);
}
System.out.println(line);
y++;
}
return map;
} catch(FileNotFoundException e) {
e.printStackTrace();
}
这可以有效地解决出现的问题。 如果没有,请给我们评论!
Jarod。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.