Java 处理数组时,变量可能尚未初始化

Java 处理数组时,变量可能尚未初始化,java,Java,在我创建的一个方法中,我试图创建一个返回用户输入字符串数组的方法。我遇到的问题是编译器说,userData不能在userData[I]=tempData处初始化和at返回用户数据。我不确定为什么会发生此错误,并希望得到一些反馈 public String[] getStringObj() { int i = 0; String tempData; String[] userData; Boolean exitLoop = false; System.out

在我创建的一个方法中,我试图创建一个返回用户输入字符串数组的方法。我遇到的问题是编译器说,
userData
不能在
userData[I]=tempData处初始化
和at
返回用户数据。我不确定为什么会发生此错误,并希望得到一些反馈

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[]userData=newstring[length]
。如果不确定长度,为了提高代码质量,您可能只想使用
阵列列表

  • 您不需要该
    exitLoop
    标志;照办

    while(true) {
        String input = IO.readString();
        if(input.equals("!")) {
            break;
        }
        /* rest of code */
    }
    
  • 由于您似乎只想无限制地将内容添加到数组中,因此请使用
    ArrayList
    而不是数组(额外的好处是,这样也可以去掉
    i
    ):

    List userData=new ArrayList();
    ...
    userData.add(行);
    

  • 如果您做了这两件事,您的代码将更加简洁和易于理解。

    这次编译器的可能副本是正确的。变量未初始化我不想限制用户可以输入多少字符串值。是否有一种方法可以输入任意大的长度数字,然后重新调整大小以删除尾部的空值?为此,您最好使用
    ArrayList
    -当元素添加到
    ArrayList
    ,其容量会自动增长。
    List<String> userData = new ArrayList<String>();
    ...
    userData.add(line);