java - 对如何将 txt 文件写入字符串然后将其转换为二维数组感到困惑
问题描述
所以我试图写一个看起来像这样的txt文件
8 7
1 1 1 1 1 1 1
1 0 0 0 e 1 1
1 0 1 0 0 1 1
1 0 1 0 1 0 1
1 0 0 0 0 0 1
1 0 0 1 0 0 1
1 0 1 0 1 s 1
1 1 1 1 1 1 1
而且我无法将前两个数字作为数组的大小,然后将其余数字转换为字符串,然后将该字符串转换为具有所有这些值的二维数组。谢谢!
while (input.hasNext()) {
numRows = input.nextInt();
numCols = input.nextInt();
input.nextLine();
String s = "";
for (int i = 0; i < numRows; i++)
s = s + input.nextLine();
int place = 0;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
maze[numRows][numCols] = String.valueOf(s.charAt(place));
place++;
}
}
}
解决方案
你没有索引。使用您已定义i
的索引。j
这是使用索引正确迭代的示例:
矩阵.txt
8 7
1 1 1 1 1 1 1
1 0 0 0 e 1 1
1 0 1 0 0 1 1
1 0 1 0 1 0 1
1 0 0 0 0 0 1
1 0 0 1 0 0 1
1 0 1 0 1 s 1
1 1 1 1 1 1 1
主.java
public class Main {
public static void main(String[] args) throws IOException {
char[][] matrix = null; // change to String[][] matrix = null; if you want Strings
try (Scanner s = new Scanner(Path.of("matrix.txt"))) {
int rows = s.nextInt();
int cols = s.nextInt();
s.nextLine();
matrix = new char[rows][cols]; // change to matrix = new String[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = s.next().charAt(0); // change to matrix[i][j] = s.next();
}
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
输出:
1 1 1 1 1 1 1
1 0 0 0 e 1 1
1 0 1 0 0 1 1
1 0 1 0 1 0 1
1 0 0 0 0 0 1
1 0 0 1 0 0 1
1 0 1 0 1 s 1
1 1 1 1 1 1 1
我还为您想要 aString[]
而不是 a的情况添加了建议char[]
。
推荐阅读
- java - 如何使用 Firestore 查询的结果填充微调器?
- c# - Linq C# linq group by into 查询结果与 SQL 中的查询不同
- java - 使用 Thymeleaf 为文件夹中的 CSS 文件动态生成链接标签
- javascript - 单个 setInterval 方法中不同 DOM 事件的 Javascript 计时器
- ms-access - MSAccess - 删除麻烦字符的更有效方法?
- ios - 3X4 带有圆形按钮的键盘,如 iPhone 手机应用程序所示,可响应所有屏幕尺寸
- python-3.x - RDS、AWS Lambda、应用程序客户端 - 设置类型
- spring - 如何使用枚举作为请求参数发出 Jmeter HTTP 请求?
- javascript - Javascript Promise,它的行为很奇怪
- sql - 计算特定行中的 Null 值