CS106A讲义6 Exception java.lang.NullPointerException

时间:2013-09-01 09:34:30

标签: java nullpointerexception

NullPointerException出错。 (cs106A讲义6 - 使用哈希映射的名称计数) 调试器告诉我@ String输入变量的问题。我不知道如何解决它。 谢谢你的阅读。

import acm.io.*;
import acm.program.*;
import acm.util.*;
import java.util.*;
import java.io.*;
import java.io.BufferedReader.*;
import java.lang.*;

public class NameCounts extends ConsoleProgram{
// hashmap 
static HashMap<String,Integer> myUniq = new HashMap<String,Integer>();
static String input ;

static public void insertName(){

    try {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while(true){
        System.out.println("Enter name:");

               // if keyboard input contain new unique name , 
               // store it in the hashmap and count the value +1
        input = br.readLine();
        if(input.equals("")) break;
        if( myUniq.containsKey(input) ==false){
            Integer temp = myUniq.get(input);
            temp = temp + 1;
            myUniq.put(input,temp);
        }

      }
    }
    catch (IOException e){ };
}
    // print and show every single hash map and count value
    static public void releaseUnique(){
            for(int i= 1 ; i < myUniq.size() ; i++){
    System.out.println("Entry"+"[" + input + "]"+"has count"+myUniq.get(input));        
            }
}

public static void main (String[] args){
    insertName();
    releaseUnique();
    }
}

errorlog

1 个答案:

答案 0 :(得分:1)

我认为你应该改变

if( myUniq.containsKey(input) ==false){
    Integer temp = myUniq.get(input);
    temp = temp + 1;
    myUniq.put(input,temp);
}

if(myUniq.containsKey(input)) {
    Integer temp = myUniq.get(input);
    temp = temp + 1;
    myUniq.put(input, temp);
} else {
    myUniq.put(input, 1);
}