[英]Variable might not have been initialized when dealing with array
在我嘗試創建的一種方法中,該方法旨在返回用戶輸入的字符串數組。 我遇到的問題是編譯器說userData
可能未在userData[i]=tempData;
處初始化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;
}
您的userData
尚未初始化,您正嘗試在此處使用它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)
您沒有初始化String[]
。 只要做String[] userData = new String[length]
。 如果不確定長度,則可能只想使用ArrayList<String>
。
為了提高代碼質量:
您不需要那個exitLoop
標志; 做就是了
while(true) { String input = IO.readString(); if(input.equals("!")) { break; } /* rest of code */ }
由於您似乎只想無限制地將內容添加到數組中,因此請使用ArrayList
而不是數組(添加的好處是,它也擺脫了i
):
List<String> userData = new ArrayList<String>(); ... userData.add(line);
如果您做這兩件事,您的代碼將更加簡潔和易於理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.