I just started learning java and now I'm trying to input a text file and make it a 2-dimensional string array. But somehow it shows no line found in the output(NoSuchElementException). So here is my code:
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);
}
and here is the main method:
public static void main(String[] args) throws Exception
{
Maze mazeobject = new Maze();
mazeobject.create();
}
So this is how the text file looks like: Maze.txt I've seen a lot of forum discussing the same questions, but none of them works for mine. Thanks in advance! I really appreciate your help.
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();
}
}
You have to make sure there are enough lines in the ./Maze.txt
as you required by Max_Maze_Row = 20 and Max_Maze_Column = 50 . Otherwise this line mazearray[i][j] = sc.nextLine();
will fail by java.util.NoSuchElementException: No line found
Change your create method like this:
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++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.