如何从Map的Element创建对象

时间:2018-05-27 17:48:27

标签: java

所以我现在有这个:

  public static JavaFact register(JavaFact jf){
    Scanner input = new Scanner(System.in);
    Map<String, Activity> activities = new HashMap<String, Activity>();
    Map<String, Activity> companyActivities = new HashMap<String, Activity>();

    activities = jf.getAllActivities //this is just to get all the existent 
   // activities into the Map activities

    System.out.println("How many activities is the user envolved in?");
    int count = input.nextInt();
    for(int i = 0; i<count; i++){
         System.out.println("Insert activity code");
         String code = input.nextLine();
         Activity a = activities.get(code);
         companyAcitivities.put(code, a.clone()); //the error refers to this line
    }
}

有了这个,我在main上运行后得到NullPointerException。我怎么解决这个问题?我想要的是让用户插入Activity的代码,然后将Activity添加到companyActivitiesMapCompany举行所有与之对应的活动问题String[] permissions = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}; getBulkPermissions(permissions, new RequestPermissionAction() { @Override public void permissionDenied() { // TODO: 5/27/2018 handle permission deny } @Override public void permissionGranted() { // TODO: 5/27/2018 you code do further operations } });

1 个答案:

答案 0 :(得分:1)

为了避免你的NullPointerException尝试这种方式,正如其他人在上面的评论中已经建议的那样:

for(int i = 0; i<count; i++){
     System.out.println("Insert activity code");
     String code = input.nextLine();
     Activity a = activities.get(code);

     if(a != null) {
         companyAcitivities.put(code, a.clone()); //the error refers to this line
     }
}