java 将值存储到字符串数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13832813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store value into string array
提问by IssacZH.
I wanted to store a value from a string array to another string array. But I get "NullPointerException" error with the code below. "imagesSelected" is a string array stored with values inside. But when i wanted to move it into another string array after substring, I get error. I believed is because of the last line of code. I'm not sure how to make it work.
我想将一个字符串数组中的值存储到另一个字符串数组中。但是我在下面的代码中收到“NullPointerException”错误。“imagesSelected”是一个字符串数组,里面存储了值。但是当我想在子字符串之后将它移动到另一个字符串数组时,我得到了错误。我相信是因为最后一行代码。我不知道如何使它工作。
String[] imageLocation;
if(imagesSelected.length >0){
for(int i=0;i<imagesSelected.length;i++){
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
回答by Ted Hopp
You need to do something like this:
你需要做这样的事情:
String[] imageLocation = new String[imagesSelected.length];
Otherwise imageLocation
will be null
.
否则imageLocation
会null
。
By the way, you don't need the if
around your loop. It's completely redundant, as that will be the same logic that will be used at the start of the loop.
顺便说一句,你不需要if
你的循环。这是完全多余的,因为这将与循环开始时使用的逻辑相同。
回答by user1896670
imageLocation[i]
图像位置[i]
have you initialized imageLocation?
你初始化 imageLocation 了吗?
I believe this error is because you are trying to point to a location in the string array that does not exist. imageLocation[0,1,2,3...etc] do not exist yet because the string array has not been initialized.
我相信这个错误是因为您试图指向字符串数组中不存在的位置。imageLocation[0,1,2,3...etc] 尚不存在,因为字符串数组尚未初始化。
Try String[] imageLocation[however long you want the array to be]
试试 String[] imageLocation[无论你想要数组有多长]
回答by TieDad
You must allocate memory for imageLocation.
您必须为 imageLocation 分配内存。
imageLocation = new String[LENGTH];
回答by Bhavik Ambani
Your final solution code should be like as below, or compiler will give you an error that imageLocation
may not have been initialized
您最终的解决方案代码应该如下所示,否则编译器会给您一个imageLocation
可能尚未初始化的错误
String[] imageLocation = new String[imagesSelected != null ? imagesSelected.length : 0];
if (imagesSelected.length > 0) {
for (int i = 0; i < imagesSelected.length; i++) {
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}
回答by Mudassar Shaheen
look at this code
看看这段代码
String[] imageLocation;
if(imagesSelected.length >0){
imageLocation = new String[imageSelected.length];
for(int i=0;i<imagesSelected.length;i++){
int start = imagesSelected[i].indexOf("WB/");
imageLocation[i] = imagesSelected[i].substring(start + 3);
}
}