英文:
Convert 2 text line of integers into 2D array
问题
我想将这些文本行转换为2D数组,使用BufferReader。有什么帮助吗?
英文:
I have some text lines like this
14 14 14 14
32 32 32 32
I want to convert into 2D array with BufferReader. Any help?
答案1
得分: 0
我希望你正在寻找将字符串数组转换为缓冲区的方法
public int[][] convertTo2DArray(String filename) {
int[][] array = null;
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
int row = 0;
while ((line = reader.readLine()) != null) {
String[] elements = line.split(" ");
if (array == null) {
array = new int[elements.length][];
}
array[row] = new int[elements.length];
for (int i = 0; i < elements.length; i++) {
array[row][i] = Integer.parseInt(elements[i]);
}
row++;
}
} catch (IOException e) {
e.printStackTrace();
}
return array;
}
String filename = "path/to/your/file.txt";
int[][] result = convertTo2DArray(filename);
英文:
I am hoping you are looking for convert string array in buffer
public int[][] convertTo2DArray(String filename) {
int[][] array = null;
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
int row = 0;
while ((line = reader.readLine()) != null) {
String[] elements = line.split(" ");
if (array == null) {
array = new int[elements.length][];
}
array[row] = new int[elements.length];
for (int i = 0; i < elements.length; i++) {
array[row][i] = Integer.parseInt(elements[i]);
}
row++;
}
} catch (IOException e) {
e.printStackTrace();
}
return array;
}
String filename = "path/to/your/file.txt";
int[][] result = convertTo2DArray(filename);
答案2
得分: 0
通过使用BufferedReader的lines()方法拆分您的行,然后可以使用映射将数字按空格拆分。(使用这个正则表达式可以在有多个空格字符的情况下拆分)
String input = "14 14 14 14\n32 32 32 32\n";
BufferedReader reader = new BufferedReader(new StringReader(input));
int[][] array = reader.lines()
.map(line -> Arrays.stream(line.split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
英文:
By splitting your lines with the lines() method of BufferedReader, you can then use a map to split numbers with spaces. (using this regular expression allows to split even if there is more than one space character)
String input = "14 14 14 14\n32 32 32 32\n";
BufferedReader reader = new BufferedReader(new StringReader(input));
int[][] array = reader.lines()
.map(line -> Arrays.stream(line.split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论