簡體   English   中英

處理數組時,變量可能尚未初始化

[英]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>

為了提高代碼質量:

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

如果您做這兩件事,您的代碼將更加簡潔和易於理解。

暫無
暫無

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

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