2012-10-24 41 views
0

在我創建的方法中,我嘗試創建的方法旨在返回用戶輸入字符串的數組。我有編譯器的問題是說userData可能不會被初始化爲userData[i]=tempData;return userData;。我不確定這個錯誤發生的原因,並希望得到一些反饋。在處理數組時,變量可能未被初始化

public String[] getStringObj() { 
    int i = 0; 
    String tempData; 
    String[] userData; 
    Boolean exitLoop = false; 
    System.out.println("Please list your values below, separating each item using the return key. To exit the input process please type in ! as your item."); 
    do { 
     tempData = IO.readString(); 
     if (tempData.equals("!")) { 
      exitLoop=true; 
     } else { 
      userData[i] = tempData; 
      i++; 
     } 
    } while (exitLoop == false); 
    return userData; 
} 
+1

可能重複的[變量可能未被初始化錯誤](http://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – epoch

+0

編譯器這次是正確的。 _variable未初始化_ – manas

回答

0

在提高代碼質量的興趣:

  1. 你並不需要一個exitLoop標誌;只是做

    while(true) { 
        String input = IO.readString(); 
        if(input.equals("!")) { 
         break; 
        } 
        /* rest of code */ 
    } 
    
  2. 既然你看起來像你想只是添加東西到一個數組沒有界限,使用ArrayList而不是數組(額外的獎勵,這擺脫的i太):

    List<String> userData = new ArrayList<String>(); 
    ... 
    userData.add(line); 
    

如果你做了這兩件事情,你的代碼將更加簡潔和易於遵循。

0

userData不initilaized和你正試圖初始化之前這裏userData[i]=tempData;使用它。

初始化它作爲

String[] userData = new String[20]; 

//20 is the size of array that I specified, you can specify yours 

而且在你while條件你可以有while(!exitLoop)代替while(exitLoop==false)

+0

我不想限制用戶可以輸入多少個字符串值。有沒有一種方法可以將長度設置爲任意大的數字,然後重新調整大小以刪除拖尾的空值? – nonterrorist

+0

爲了更好地使用'ArrayList'-當元素被添加到'ArrayList'時,它的容量會自動增長。 – Abubakkar

0

你沒有初始化String[]。請做String[] userData = new String[length]。如果您不確定長度,您可能只想使用ArrayList<String>