即使已初始化,也会出现“可变数据未初始化”错误

时间:2015-03-18 18:51:54

标签: java arrays filereader

我有一段时间没碰过Java,所以我对一些细节有些生疏。

我正在尝试从一个充满数字的文件中读取所有内容。文件中的第一个数字告诉我文件中有多少其他数字,所以我可以适当调整我的数组大小。我试图获取这些数字并将它们放入一个int数组中,但我不断得到"错误:可变数据可能尚未初始化"在我的回复声明中。我知道这必须是简单的事情,但我不能为我的生活找出我做错的简单事情。

public static int[] numbers(String filename)
{
    int[] data;

    try
    {
        FileReader input = new FileReader(filename);
        BufferedReader buffer = new BufferedReader(input);

        int arraySize = Integer.parseInt(buffer.readLine());
        data = new int[arraySize];

        for (int x = 0; x < arraySize; x++)
        {
            data[x] = Integer.parseInt(buffer.readLine());
        }

        buffer.close();
    }

    catch(Exception e)
    {
        System.out.println("Error reading: "+e.getMessage());
    }

    return data;
}

4 个答案:

答案 0 :(得分:5)

如果try块中出现异常,则data可能在返回时尚未初始化。

在声明它时将其初始化为某个值,即使值为null,也要满足编译器。

另一方面,看起来IOException是唯一被抛出的例外。或者,您可以声明您的方法抛出IOException,并删除try - catch块,以便data语句始终初始化return被执行。您当然需要在调用numbers方法的方法中捕获异常。

答案 1 :(得分:3)

您收到此错误是因为您正在初始化try块内的数据数组,但如果您的try块捕获异常,则数据数组可能无法初始化但无论如何都会被退回。

在try-catch之外初始化数组:

例如:

 int[] data = new int[1]; //default initialization

答案 2 :(得分:2)

这是由于try / catch块中的初始化,如果在try / catch块中初始化之前抛出异常,则该数组可能永远不会被实例化。

我认为只需将数组长度设置为1或声明为null就可以解决问题

int[] data = new int[1];
try
// the rest

int[] data = null;

答案 3 :(得分:0)

我有两条建议与其他答案略有不同(只是略有不同)。如果存在异常,那么您应该1)抛出异常(例如RuntimeException)或2)只返回null(我的猜测是你不希望异常实际上是抛出)。

public static int[] numbers(String filename)
{
    BufferedReader buffer = null;
    try
    {
        final FileReader input = new FileReader(filename);
        BufferedReader buffer = new BufferedReader(input);

        final int arraySize = Integer.parseInt(buffer.readLine());
        final int[] data = new int[arraySize];

        for (int x = 0; x < arraySize; x++)
        {
            data[x] = Integer.parseInt(buffer.readLine());
        }

        buffer.close();
        return data;
    }
    catch(Exception e)
    {
        System.out.println("Error reading: "+e.getMessage());
    }
    finally{
        // a NumberFormatException may be thrown which will leave
        //   the buffer open, so close it just in case
        if(buffer != null)
            buffer.close();
    }
    // else there was an exception, return null
    return null;
}
相关问题