我正在制作这个方法remove(),它接受一个String字作为参数,从全局数组中删除“单词”,但由于某些我无法找到的原因,我一直遇到NullPointerException。
基本上我检查单词是否在第一个位置,否则如果在最后一个位置,或者如果它不在,那么我检查所有数组,并在单词的位置之前添加前半部分,然后在数组中单词的位置后添加后半部分,以跳过它并“删除它”。但是我在for循环中得到一个NullPointerException来查找数组中单词的位置。该方法的代码如下:
public void remove(String a){
String[] temp_arr = new String[words.length-1]; // make array with 1 less length for deleted
if(words[0].equals(a)){ // if the word is the first in the array
for(int x=0, z=1; x<temp_arr.length; x++,z++)
temp_arr[x]=words[z];
words = temp_arr;
} else if(words[words.length-1].equals(a)){ // if the word is in the last position of the array
for(int x=0, z=0; x<temp_arr.length; x++,z++)
temp_arr[x] = words[z];
words = temp_arr;
} else{ // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop, in the if(words[k].equals(a))
int k=0;
for (; k<words.length; k++){ // find the position of the word to delete
if (words[k].equals(a)) {
break;
}
}
for (int i = 0; i < k-1; i++){ // add first part of array before the word
temp_arr[i] = words[i];
}
for(int c = k, b = k+1; c< temp_arr.length; c++,b++){
temp_arr[c] = words[b];
}
words = temp_arr; // assign the new values to global array
}
}
此外,如果有任何关于良好编码实践的建议将不胜感激,谢谢!
**我只能使用Arrays作为此方法的数据结构。
答案 0 :(得分:2)
像这样修改条件
a.equals(字[0])
因为你知道字符串值a。但不知道阵列会有什么价值。因此,即使null值来自数组,它也允许空指针异常。
答案 1 :(得分:1)
我运行你的代码并发现一些错误,我在不改变核心思想的情况下纠正了一些错误: } else {//如果单词不在数组的第一个或最后一个位置
// THIS IS WHERE the exception is thrown, in this for loop.
int k = -1;
for (int i = 0; i < words.length; i++) { // find the position of the word to delete
if (words[i].equals(a)) {
k=i;
break;
}
}
if(k<0)//if not exists
return;
for (int i = 0; i < k /*- 1*/; i++) { // add first part of array before the word
temp_arr[i] = words[i];
}
for (int i = k; i < temp_arr.length; i++) {
temp_arr[i] = words[i+1];
}
words = temp_arr; // assign the new values to global array
}
如果原始数组不能有null元素,我会这样做:
public static String[] remove(String words[] , String a) {
int counter = 0;
for (int i = 0; i < words.length; i++) {
if( a.equals(words[i]) ){
words[i] = null;
counter++;
}
}
if(counter==0){
return words;
}
String[] words2 = new String[words.length - counter];
int i=0;
for (String string : words) {
if(string!=null){
words2[i++]=string;
}
}
return words2;
}
答案 2 :(得分:0)
我会这样做:
public void remove(String a) {
List<String> tmp = new ArrayList<String>();
for (String word : words) {
if ((word != null) && (word.equals(a))) {
continue;
}
tmp.add(word);
}
words = tmp.toArray(new String[]);
}
答案 3 :(得分:0)
我有一个问题:
为什么你为什么要使用阵列?你应该总是使用一个集合(例如List
),除非你绝对必须使用一个数组(确实很少见)。
如果是List
,您甚至不需要这种方法,因为List
有remove()
方法可以为您完成所有这些!