找不到符号2d数组返回问题

问题描述 投票:0回答:1

我正在尝试使用文本文件的内容创建一个二维数组,但我无法返回它。它说它无法找到符号firstDimension,但是我在方法中声明了它。

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

public class Map {
    public static char[][] readFile() {
        try {
            List<String> list = new ArrayList<String>();

            String thisLine = null;
            BufferedReader br;
            br = new BufferedReader(new FileReader("map.txt"));

            while ((thisLine = br.readLine()) != null) {
                list.add(thisLine);
            }

            char[][] firstDimension = new char[list.size()][];
            for (int i = 0; i < list.size(); i++) {
                firstDimension[i] = list.get(i).toCharArray();
            }

            for (int i=0; i < firstDimension.length; i++) {
                for (int j=0; j < firstDimension[i].length; j++) {
                    System.out.print(firstDimension[i][j]);
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return firstDimension;
    }
}
java arrays 2d
1个回答
1
投票

firstDimension在try块中声明,因此其范围是try块。为了能够在try块之外返回它,你需要声明如下:

public static char[][] readFile() {
    char[][] firstDimension = null;
    try {
        List<String> list = new ArrayList<String>();

        String thisLine = null;
        BufferedReader br;
        br = new BufferedReader(new FileReader("map.txt"));

        while ((thisLine = br.readLine()) != null) {
            list.add(thisLine);
        }

        firstDimension = new char[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            firstDimension[i] = list.get(i).toCharArray();
        }

        for (int i=0; i < firstDimension.length; i++) {
            for (int j=0; j < firstDimension[i].length; j++) {
                System.out.print(firstDimension[i][j]);
            }
            System.out.println();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return firstDimension;
}

在这种情况下,如果遇到异常,您的方法可能会返回null。

这是another example of the same issue

© www.soinside.com 2019 - 2024. All rights reserved.