[英]Read strings from .txt file to and put contents into a 2d array
Hi, so I am supposed to read the lines from a text file, and output the data into a 2D array, I have read the lines but I am confused as to how to input the contents to the 2D array. 嗨,我应该从文本文件中读取行,并将数据输出到2D数组中,我已经阅读了行,但是对于如何将内容输入2D数组感到困惑。
This is the file : 这是文件:
eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply
wnarmupnke
ngrelclene
alytueyuei
fgrammarib
tdcebykxka
My problem is how do I put these strings into the the 2d array as shown below. 我的问题是如何将这些字符串放入2d数组中,如下所示。
public class WordFinder {
public static final int N = 10;
public static char[][] grid = new char[N][N];
public static final String GRID_FILE = "grid.txt";
public static void initGrid() {
try {
File file = new File(GRID_FILE);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
I am quite new to JAVA, so any help would be much appriciated! 我对JAVA还是很陌生,所以对您的帮助非常有用!
Here's a quick modification to your code to make it work. 这是对您的代码的快速修改,以使其正常工作。 Read a line as a string, then iterate over the characters in the string and place them in the char[][]
array. 将一行读取为字符串,然后遍历字符串中的字符,并将其放置在char[][]
数组中。
import java.util.*;
import java.io.*;
public class WordFinder {
public static final int N = 10;
public static char[][] grid = new char[N][N];
public static final String GRID_FILE = "grid.txt";
public static void initGrid() {
try {
File file = new File(GRID_FILE);
Scanner scanner = new Scanner(file);
for (int i = 0; scanner.hasNext(); i++) {
String line = scanner.next();
for (int j = 0; j < N; j++) {
grid[i][j] = line.charAt(j);
}
}
scanner.close();
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
public static void main(String[] args) {
initGrid();
for (char[] row : grid) {
for (char cell : row) {
System.out.print(cell);
}
System.out.println();
}
}
}
Output: 输出:
eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply
wnarmupnke
ngrelclene
alytueyuei
fgrammarib
tdcebykxka
Careful, though: this design can crash on input files that are something other than a 10x10 grid of chars. 不过请小心:此设计可能会在输入文件(非10x10字符网格)上崩溃。 Consider using an ArrayList to dynamically match the size of your text file, or at least you may add to your error handling: 考虑使用ArrayList动态匹配文本文件的大小,或者至少可以添加到错误处理中:
catch (FileNotFoundException | ArrayIndexOutOfBoundsException e) {
System.out.println("Something terrible happened.");
System.exit(1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.