繁体   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