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