簡體   English   中英

即使已初始化“可變數據未初始化”錯誤

[英]Getting “Variable data not initialized” error even though it's initialized

我已經有一段時間沒有接觸Java了,所以在某些細節上我有些生疏。

我試圖從一個充滿數字的文件中讀取所有數據。 文件中的第一個數字告訴我文件中還有多少個其他數字,因此我可以適當地調整數組大小。 我試圖將這些數字放入一個整數數組中,但是我在return語句中不斷收到“錯誤:變量數據可能尚未初始化”。 我知道這一定很簡單,但是我無法終生發現自己在做錯什么簡單的事情。

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

如果try塊中引發了異常,則data可能在返回時尚未初始化。

聲明它時將其初始化為某種值,即使該值為null ,也可以滿足編譯器的要求。

另一方面, IOException是唯一要拋出的異常。 或者,您可以聲明您的方法引發IOException ,並刪除try - catch塊,以便在執行return語句時始終初始化data 您當然需要在調用您的numbers方法的方法中捕獲異常。

之所以會出現此錯誤,是因為您正在try塊中初始化數據數組,但是如果try塊捕獲到異常,則該數據數組可能不會初始化,但無論如何都會返回。

在try-catch之外初始化數組:

例如:

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

這是由於在try / catch塊中進行了初始化,如果在try / catch塊中進行初始化之前引發了異常,則可能永遠無法實例化該數組。

我認為只需在聲明中將數組長度設置為1或null即可解決您的問題

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

要么

int[] data = null;

我有兩個與其他答案稍有不同的建議(僅略有不同)。 如果存在異常,那么您應該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;
}

暫無
暫無

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

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