gpt4 book ai didi

java - 如何从输入文本文件中获取行和列的大小?

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:20 24 4
gpt4 key购买 nike

我想从此文件文本中获取行和列的长度。我怎样才能做到这一点?谢谢!

in.txt

2 1 1 8

1 1 4 15

0 3 2 9

public static void main(String[] args) {

int[][] arr = new int[3][4];

File inputFile = new File("in.txt");
try {
Scanner scanF = new Scanner(inputFile);

for (int i = 0; i < 3; i++) {
String line = scanF.nextLine();
String valVar[] = line.split(" ");
for (int j = 0; j < 4; j++) {
arr[i][j] = Integer.parseInt(valVar[j]);

}
}

} catch (Exception e) {
e.printStackTrace();
}

}

最佳答案

您还可以使用缓冲阅读器。

            int maxRows = 0;
int maxColumn = 0;
try {
Scanner scanF = new Scanner(inputFile);
String line = scanF.nextLine();
while (line != null) {
if (line.trim().length() > 0) {
maxRows++;
String valVar[] = line.split(" ");
if (maxColumn < valVar.length) {
maxColumn = valVar.length;
}
}
try {
line = scanF.nextLine();
} catch (NoSuchElementException e) {
break;
}
}

} catch (Exception e) {
e.printStackTrace();
}

关于java - 如何从输入文本文件中获取行和列的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com