java.util.scanner with chars



我正在尝试使用面向对象编程创建一个迷宫查找算法。我把迷宫存储在一个文件中,我希望文件能够读取迷宫并在解决它们之前将它们打印出来(好像用其他方法更容易,但我必须使用文件阅读器)。但是,我的charAt函数不起作用,我不确定如何使fileReader读取字符。如果有人能提供一个解决方案,那就太好了:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static Maze maze;
public static void main(String[] args) {
ArrayList<char[]> mazeArray = new ArrayList<char[]>();
try {
File myMaze = new File("maze.txt");
Scanner fileReader = new Scanner(myMaze);
while (fileReader.hasNextLine()) {
char[] mazeLayout = new char[(int) myMaze.length()];
for (int i = 0; i < Integer.MAX_VALUE; i++){
for (int j = 1; j < myMaze.length(); j++){
mazeLayout[i] = fileReader.next().charAt(j);
mazeArray.add(mazeLayout);
}
}
}
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist.");
e.printStackTrace();
}
maze = new Maze(mazeArray);
maze.print();
}
}

最好有样例文件数据来查看正在读取的内容,因为在这一点上…我只能猜测。如果文件内容如下所示:

xx xxxxxxx
xx  xxxxxx
xxx xxxxxx
xxxx    xx
xxxxx x xx
xxxx  x  x
xxxx xxx x
xxxxxx   x
xxxxx  xxx
xxxxx xxxx

则不需要char[]数组,只需将每行存储到数组列表中,然后将其存储为String (ArrayList<String>)的数组列表。现在只需将数组列表中的每个元素打印到控制台窗口。我不知道,所以…我们将假设它就像上面的一样,但是我们将每一行都转换为char[]数组,因为您似乎想要对字符执行此操作。考虑到这一点……

需要做什么:

  1. 逐行读取文件
  2. 读取每一行并将其转换为char数组
  3. 将此数组添加到mazeArray数组列表中。
  4. 将ArrayList (mazeArray)的内容打印到控制台窗口。
// ArrayList to hold the Maze from file.
ArrayList<char[]> mazeArray = new ArrayList<>();
// `Try With Resources` used here to auto-close reader and free resources.
try (Scanner fileReader = new Scanner(new File("maze.txt"))) {

// String variable to hold each line read in
String line;
// Loop through the whole file line by line...
while (fileReader.hasNextLine()) {

// Task 1: Apply current line read to the `line` variable.
line = fileReader.nextLine().trim(); // Remove any leading/trailing spaces as well.

// Make sure the line isn't blank (if any). You don't want those.
if (line.isEmpty()) {
continue;  // Go to the top of loop and read in next line.
}

// Task #2: Convert the String in the variable `line` to a char[] array.
char[] chars = line.toCharArray();

// Task #3: Add the `chars` character array to the `mazeArray` ArrayList.
mazeArray.add(chars);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(yourClassName.class.getName()).log(Level.SEVERE, null, ex);
}
/* Task #4: Print the maze contained within the `mazeArray` ArrayList
to the Console Window.       */
// Outer loop to get each char[] array within the ArrayList.
for (char[] characters : mazeArray) {
// Inner loop to get each character within the current char[] array.
for (char c : characters) {
System.out.print(c); //Print each character on the same console row.
}
System.out.println(); // Start a new line in console.
} 

相关内容

  • 没有找到相关文章

最新更新