Java-使用扫描仪将文本文件读入2D字符数组
我正在尝试将文本文件读入30x30字符数组。Scanner没有nextChar方法,所以我假设我将使用next(),然后将该行拆分为字符?不过,我很想用3个for循环来实现这一点,一个用于字符串,一个用于行,一个用于列 这是我到目前为止的代码Java-使用扫描仪将文本文件读入2D字符数组,java,arrays,java.util.scanner,Java,Arrays,Java.util.scanner,我正在尝试将文本文件读入30x30字符数组。Scanner没有nextChar方法,所以我假设我将使用next(),然后将该行拆分为字符?不过,我很想用3个for循环来实现这一点,一个用于字符串,一个用于行,一个用于列 这是我到目前为止的代码 public static void main(String[] args) throws FileNotFoundException { final int cellSize = 30; // grid size char[][] cha
public static void main(String[] args) throws FileNotFoundException {
final int cellSize = 30; // grid size
char[][] chargrid = new char[cellSize][cellSize];
File inputFile = new File("E:\\workspace\\Life2\\bin\\Sample input.txt");
Scanner in = new Scanner(inputFile);
char testchar;
while(in.hasNext()){
String s = in.next();
for (int i=0; i<s.length();i++){
testchar = s.charAt(i);
publicstaticvoidmain(字符串[]args)抛出FileNotFoundException{
final int cellSize=30;//网格大小
char[][]chargrid=new char[cellSize][cellSize];
File inputFile=新文件(“E:\\workspace\\Life2\\bin\\Sample input.txt”);
扫描仪输入=新扫描仪(输入文件);
字符testchar;
while(在.hasNext()中){
字符串s=in.next();
对于(int i=0;i据我在你的评论中看到的,如果字符是“X”,你也希望有一个带有布尔值的2D数组,所以我在代码中填充了两个数组——一个是字符,另一个是真或假,这取决于字符是否是“X”。还有一些system.out可以更好地理解它的工作原理。我正在删除换行符出现时的字符('\n')(不知道是否需要)
顺便说一句,我正在从输入流中逐个字符地读取字符,而不是使用扫描仪,希望可以,否则请告诉我
无论如何,这可能是好的为什么你要尝试将文本文件读入一个30x30字符数组,为什么不简单地读入一个列表
?我真正想做的是拥有一个30x30布尔数组,如果char='X',那么该单元格将为真,但我甚至无法让它将文本文件读入数组,更不用说这样做了我建议您首先读取列表中的文件,然后检查该列表以填充30x30布尔数组。
public static void main(String[] args) {
final int cellSize = 30; // grid size
char[][] chargrid = new char[cellSize][cellSize];
boolean[][] chargridIsX = new boolean[cellSize][cellSize];
File inputFile = new File("input.txt");
FileInputStream is = null;
try {
is = new FileInputStream(inputFile);
int n = -1;
int rowCount = 0;
int colCount = 0;
while( (n=is.read()) !=-1){
char readChar = (char) n;
if(readChar!='\n'){//This removes the linebreaks - dont know if you want that
chargrid[rowCount][colCount] = readChar;
if(readChar=='X') { // Here actually set true or false if character is 'X'
chargridIsX[rowCount][colCount] = true;
System.out.println("row "+rowCount+" col "+colCount + " = " + readChar + " " + true);
}else {
chargridIsX[rowCount][colCount] = false;
System.out.println("row "+rowCount+" col "+colCount + " = " + readChar+ " " + false);
}
if(rowCount++ >= cellSize-1){
System.out.println("new col");
rowCount = 0;
if(colCount++ >= cellSize-1){
//ARRAY IS FULL
System.out.println("full");
break;
}
}
}
}
} catch (FileNotFoundException e) {
//could not get Inputstream from file
e.printStackTrace();
} catch (IOException e) {
// problem with the inputstream while reading
e.printStackTrace();
}