簡體   English   中英

使用Java從文本文件創建2D數組

[英]Create 2D array from text file in Java

我剛剛開始學習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我見過很多論壇都在討論相同的問題,但是它們都不適用於我的問題。 提前致謝! 非常感謝您的幫助。

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();
    }
}

你必須確保有足夠的線路中的./Maze.txt為您Max_Maze_Row = 20,Max_Maze_Column = 50必需的。 否則,此行mazearray[i][j] = sc.nextLine(); 將因java.util.NoSuchElementException: No line found而失敗java.util.NoSuchElementException: No line found

像這樣更改您的創建方法:

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++;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM