[英]Why am I receiving a null pointer exception?
When I call the calculateStringValue
method on any string within the main method, it works perfectly fine. 当我称之为
calculateStringValue
方法上的主要方法中的任何字符串,它完美的罚款。 When I try to call the method within the printStringsWithValues
method, I get a null pointer exception. 当我尝试在
printStringsWithValues
方法中调用该方法时,出现空指针异常。 Does this have something to do with the string being in an ArrayList
? 这与
ArrayList
的字符串有关吗?
public static void main(String[] args){
List<String> testList = new ArrayList<>();
testList.add("apple");
testList.add("hello");
printStringsWithValues(testList);}
public static void printStringsWithValues(List<String> strings)
{
for (String string : strings) {
System.out.println(string + ", " + calculateStringValue(string));
}
}
public static int calculateStringValue(String word)
{
int value = 0;
for(int j=0; j < word.length(); j++)
{
if(letterValueMap.containsKey(word.charAt(j)))
{
value += letterValueMap.get(word.charAt(j));
}
else{
return -1;
}
}
return value;
}
Using a contextual inference of the type of letterValueMap I assume that it is a Map<Character, Integer>
, so I tried to create such kind of map and assign some arbitrary values in order to test your code. 通过使用letterValueMap类型的上下文推断,我假定它是
Map<Character, Integer>
,因此我尝试创建这种类型的映射并分配一些任意值以测试您的代码。
Here is what I did 这是我所做的
First declare a letterValueMap variable and then feed it with some values using a static initialization block 首先声明一个letterValueMap变量,然后使用静态初始化块为它提供一些值
public class NullPointerHandler {
private static Map<Character, Integer> letterValueMap;
static {
letterValueMap = new HashMap<Character, Integer>();
for (int i = 'a'; i<= 'a'+25; i++) {
letterValueMap.put((char)i, i);
}
for (int i = 'A'; i<= 'A'+25; i++) {
letterValueMap.put((char)i, i);
}
letterValueMap.put(' ', 32);
}
Then I simply use the other part of your code unchanged (except that I have added a few more words for testing purpose)! 然后,我只是简单地使用代码的另一部分(除了为测试目的添加了更多的单词)!
public static void main(String[] args){
List<String> testList = new ArrayList<String>();
testList.add("apple");
testList.add("hello");
testList.add("ROME");
testList.add("rome");
testList.add("Julius Cesar");
printStringsWithValues(testList);
}
public static void printStringsWithValues(List<String> strings)
{
for (String string : strings) {
System.out.println(string + ", " + calculateStringValue(string));
}
}
public static int calculateStringValue(String word)
{
int value = 0;
for(int j=0; j < word.length(); j++)
{
if(letterValueMap.containsKey(word.charAt(j)))
{
value += letterValueMap.get(word.charAt(j));
}
else{
return -1;
}
}
return value;
}
}
Testing it gives me the expected results, without generating any null pointer exception 测试它可以得到预期的结果, 而不会产生任何空指针异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.