首先,感谢您的到来并花时间帮助解决问题。
我花了无数个小时搜索,但仍然没有找到解决问题的方法:如何使用扫描仪将.txt文件中每行字符串中的单个字符扫描成未知尺寸的二维数组?
问题 1:如何确定未知.txt文件的列数?或者有没有更好的方法使用 .nextInt() 方法确定未知 2d 数组的大小以及如何确定?
问题 2:如何在控制台上打印出 2D 数组而不会出现奇怪的 [@#$^@^^ 错误?
问题 3:如何让扫描仪将从.txt文件中读取的任何字符打印到控制台上(使用 2D 数组(是的,我知道,数组的数组))?
这是我不完整的代码,可以让您了解问题:
import java.util.Scanner;
import java.io.File;
public class LifeGrid {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new File("seed.txt"));
int numberOfRows = 0, columns = 0;
while (scanner.hasNextLine()) {
scanner.nextLine();
numberOfRows++;
}
char[][] cells = new char[numberOfRows][columns];
String line = scanner.nextLine(); // Error here
for (int i = 0; i < numberOfRows; i++) {
for(int j = 0; j < columns; j++) {
if (line.charAt(i) == '*') {
cells[i][j] = 1;
System.out.println(cells[i][j]);
}
}
}
System.out.println(numberOfRows);
System.out.println(columns);
}
}
扫描仪
一旦使用就无法重置到起始位置。您必须再次创建新实例。我已经修改了您的代码以实现您正在尝试做的事情 -
import java.util.Scanner;
import java.io.File;
public class LifeGrid {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new File("seed.txt"));
int numberOfRows = 0, columns = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if( s.length() > columns ) columns = s.length();
numberOfRows++;
}
System.out.println(numberOfRows);
System.out.println(columns);
char[][] cells = new char[numberOfRows][columns+1];
scanner = new Scanner(new File("seed.txt"));
for (int i = 0; i < numberOfRows; i++) {
String line = scanner.nextLine();
System.out.println("Line="+line+", length="+line.length());
for(int j = 0; j <= line.length(); j++) {
if( j == line.length() ) {
cells[i][j] = (char)-1;
break;
}
cells[i][j] = line.charAt(j);
}
}
System.out.println(numberOfRows);
System.out.println(columns);
for (int i = 0; i < numberOfRows; i++) {
for(int j = 0; j <= columns; j++) {
if( cells[i][j] == (char)-1 ) break;
System.out.println("cells["+i+"]["+j+"] = "+cells[i][j]);
}
}
}
}