有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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添加到companyActivities中,其中将包含与所讨论的Company对应的所有活动的Map


共 (1) 个答案

  1. # 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
         }
    }