将.txt文件中的数字读入二维数组并在控制台上打印 [英] Reading numbers from a .txt file into a 2d array and print it on console
本文介绍了将.txt文件中的数字读入二维数组并在控制台上打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以基本上,我试图读取一个包含以下内容的.txt文件:
So basically i am trying to read a .txt file that contains these following in it:
3 5
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
并将它们存储到2D数组中并在控制台上打印,我从控制台获得的信息很好,但只缺少第一行3 5,我不知道我的代码有什么问题,因此忽略了第一行. 我现在得到的输出是什么:
and store them into 2D array and print it on console, what i got from the console is fine but only missing the first row 3 5, which i do not know what is wrong with my code made it ignored the first line. what i got as output now:
2 3 4 5 10
4 5 2 3 7
-3 -1 0 1 5
import java.io.*;
import java.util.*;
public class Driver0 {
public static int[][] array;
public static int dimension1, dimension2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Project 0.");
System.out.println("What is the name of the data file? ");
String file = input.nextLine();
readFile(file);
}
public static void readFile(String file) {
try {
Scanner sc = new Scanner(new File(file));
dimension1 = sc.nextInt();
dimension2 = sc.nextInt();
array = new int[dimension1][dimension2];
while (sc.hasNext()) {
for (int row = 0; row < dimension1; row++) {
for (int column = 0; column < dimension2; column++) {
array[row][column] = sc.nextInt();
System.out.printf("%2d ", array[row][column]);
}
System.out.println();
}
}
sc.close();
}
catch (Exception e) {
System.out
.println("Error: file not found or insufficient requirements.");
}
}
}
推荐答案
您可以使用Stream API轻松实现
You can use Stream API to do it easily
public static Integer[][] readFile(String path) throws IOException {
return Files.lines(Paths.get(path)) // 1
.filter(line -> !line.trim().isEmpty()) // 2
.map(line -> Arrays.stream(line.split("[\\s]+")) // 3
.map(Integer::parseInt) // 4
.toArray(Integer[]::new)) // 5
.toArray(Integer[][]::new); // 6
}
- 将文件读取为行流
- 忽略空行
- 用空格将每一行分开
- 解析拆分的String值以获取Integer值
- 创建一个整数值数组
- 以2D数组收集它
这篇关于将.txt文件中的数字读入二维数组并在控制台上打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文