0

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();
    }
}

错误日志

4

1 回答 1

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);
}
于 2013-09-01T10:14:11.607 回答