簡體   English   中英

將.txt文件中的字符串讀取到並將內容放入二維數組

[英]Read strings from .txt file to and put contents into a 2d array

嗨,我應該從文本文件中讀取行,並將數據輸出到2D數組中,我已經閱讀了行,但是對於如何將內容輸入2D數組感到困惑。

這是文件:

eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply    
wnarmupnke 
ngrelclene 
alytueyuei 
fgrammarib 
tdcebykxka

我的問題是如何將這些字符串放入2d數組中,如下所示。

public class WordFinder {
    public static final int N = 10;
    public static char[][] grid = new char[N][N];
    public static final String GRID_FILE = "grid.txt";

    public static void initGrid() {
        try {
            File file = new File(GRID_FILE);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext()) {
                System.out.println(scanner.next());
            }
            scanner.close();
            }
        catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }

我對JAVA還是很陌生,所以對您的幫助非常有用!

這是對您的代碼的快速修改,以使其正常工作。 將一行讀取為字符串,然后遍歷字符串中的字符,並將其放置在char[][]數組中。

import java.util.*;
import java.io.*;

public class WordFinder {
    public static final int N = 10;
    public static char[][] grid = new char[N][N];
    public static final String GRID_FILE = "grid.txt";

    public static void initGrid() {
        try {
            File file = new File(GRID_FILE);
            Scanner scanner = new Scanner(file);

            for (int i = 0; scanner.hasNext(); i++) {
                String line = scanner.next();

                for (int j = 0; j < N; j++) {
                    grid[i][j] = line.charAt(j);
                }
            }

            scanner.close();
        }
        catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }

    public static void main(String[] args) {
        initGrid();

        for (char[] row : grid) {
            for (char cell : row) {
                System.out.print(cell);
            }

            System.out.println();
        }
    }
}

輸出:

eoksibaebl
ropeneapop
mbrflaoyrm
gciarrauna
utmorapply
wnarmupnke
ngrelclene
alytueyuei
fgrammarib
tdcebykxka

不過請小心:此設計可能會在輸入文件(非10x10字符網格)上崩潰。 考慮使用ArrayList動態匹配文本文件的大小,或者至少可以添加到錯誤處理中:

catch (FileNotFoundException | ArrayIndexOutOfBoundsException e) {
    System.out.println("Something terrible happened.");
    System.exit(1);
}

暫無
暫無

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

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