我刚开始学习java,现在我正在尝试输入一个文本文件并使其成为一个二维字符串数组。但不知何故,它显示输出中没有找到任何行(NoSuchElementException)。 所以这是我的代码:
public class Maze {
final static int Max_Maze_Row = 20;
final static int Max_Maze_Column = 50;
public static String mazearray;
public static void create() throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader("Maze.txt")));
String [][] mazearray = new String[Max_Maze_Row][Max_Maze_Column];
while(sc.hasNextLine())
{
for(int i = 0 ;i<=Max_Maze_Row;i++)
{
for(int j = 0 ;j<=Max_Maze_Column;j++)
{
mazearray[i][j] = sc.nextLine();
System.out.println(mazearray[i][j]);
}
}
}
}
public static void display()
{
System.out.println(Maze.mazearray);
}
这是主要方法:
public static void main(String[] args) throws Exception
{
Maze mazeobject = new Maze();
mazeobject.create();
}
这就是文本文件的样子: Maze.txt 我见过很多讨论同样问题的论坛,但是没有一个能适合我的论坛。 提前致谢!我非常感谢你的帮助。
答案 0 :(得分:0)
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Scanner;
public class Maze {
final static int Max_Maze_Row = 20;
public String[] mazearray;
public void create() throws Exception {
Scanner sc = new Scanner(new BufferedReader(new FileReader("./Maze.txt")));
mazearray = new String[Max_Maze_Row];
int i = 0;
while (sc.hasNextLine()) {
mazearray[i++] = sc.nextLine();
}
}
public void display() {
System.out.println(Arrays.deepToString(mazearray));
}
public static void main(String[] args) throws Exception {
Maze mazeobject = new Maze();
mazeobject.create();
mazeobject.display();
}
}
您必须确保 Max_Maze_Row = 20 和 Max_Maze_Column = 50 所需的./Maze.txt
中足够的行>。否则此行mazearray[i][j] = sc.nextLine();
将失败java.util.NoSuchElementException: No line found
答案 1 :(得分:0)
更改您的创建方法,如下所示:
public static void create() throws Exception {
Scanner sc = new Scanner(new BufferedReader(new FileReader("Maze.txt")));
String[][] mazearray = new String[Max_Maze_Row][Max_Maze_Column];
int lineCounter = 0;
while (sc.hasNextLine()) {
String data = sc.nextLine();
for (int i = 0; i < data.length(); i++) {
mazearray[lineCounter][i] = String.valueOf(data.charAt(i));
System.out.print(mazearray[lineCounter][i]);
}
System.out.println();
lineCounter++;
}
}