java为什么main()很好地显示“Lukaku”并包含_names()返回null?
我已经创建了一个通常可以在方法“main()”和“contains_names()”中使用的hashmap,我在main的方法的hashmap中添加了一些元素,但是如果我尝试在“contains_names”中显示它们,它会返回“null”,我不明白为什么
例如: 如果我试着做这个系统。出来println(names.get(“Lukaku”))在“main”中返回0
如果我对“contains_names()”执行相同的操作,它将返回null
import java.util.HashMap;
import java.util.ArrayList;
public class devideV2 {
static int no_element=8;
public static HashMap<String,Integer> names = newHashMap<String,Integer>();
/**
*
* @param arrays is an arraylist of String which contains some names (ArrayList)
* @return the names who figure out more than an half or "null" if there's not (String)
*/
public static String contains_names(ArrayList<String> arrays){
//will return null but why ?
System.out.println(names.get("lukaku"));
//increment the value of the key that is represented by the first element of arrays
names.put(arrays.get(0),names.get(arrays.get(0)+1));
//will return True
System.out.println(names.containsKey("Lukaku"));
//At line 20 I've a null pointer Exception who has been thrown
//if the name figure out more than an half then return this name
if(names.get(arrays.get(0)) > (no_element/2)){
return arrays.get(0);
}
//remove the name
arrays.remove(0);
//making recursion
if(arrays.size()>0) {
return contains_names(arrays);
}
//if no names figure out more than an half then return "null"
return "null";
}
public static void main(String[] args){
String[] names_array={"Lukaku", "Lukaku", "Lukaku", "Hazard","Hazard","Hazard","Hazard","Hazard"};
ArrayList<String> Names_arrayList= new ArrayList<String>();
//put every names in the Hashmap and their occurences to 0
for(int i=0;i<names_array.length;i++){
Names_arrayList.add(names_array[i]);
names.put(names_array[i],0);
}
//will return 0
System.out.println(names.get("Lukaku"));
System.out.println(contains_names(Names_arrayList));
}
}
# 1 楼答案
括号中有一个拼写错误:
这是用“卢卡库1”的计数覆盖“卢卡库”,该计数不存在,因此返回null
您需要的是(具有适当的格式):