Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser…

  1. User

    private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser();

      try {
         Object obj = parser.parse(json);
         JSONObject jparser = (JSONObject)obj;
         JSONArray jarray = (JSONArray)jparser.get("items");
    
         for(int i = 0; i < jarray.size(); ++i) {
            JSONObject item = (JSONObject)jarray.get(i);
            LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en"));
            LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en"));
            String id = (String)item.get("id");
            int priceM0 = Integer.parseInt((String)item.get("price_m0"));
            int priceM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m1")) : priceM0;
            int priceM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m2")) : priceM0;
            int priceM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m3")) : priceM0;
            int rangM0 = Integer.parseInt((String)item.get("rang_m0"));
            int rangM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m1")) : rangM0;
            int rangM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m2")) : rangM0;
            int rangM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m3")) : rangM0;
            PropertyItem[] propertysItemM0 = null;
            PropertyItem[] propertysItemM1 = null;
            PropertyItem[] propertysItemM2 = null;
            PropertyItem[] propertysItemM3 = null;
            int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications"));
    
            for(int m = 0; m < countModification; ++m) {
               JSONArray propertys = (JSONArray)item.get("propertys_m" + m);
               PropertyItem[] property = new PropertyItem[propertys.size()];
    
               for(int p = 0; p < propertys.size(); ++p) {
                  JSONObject prop = (JSONObject)propertys.get(p);
                  property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value"));
               }
    
               switch(m) {
                  case 0:
                     propertysItemM0 = property;
                     break;
                  case 1:
                     propertysItemM1 = property;
                     break;
                  case 2:
                     propertysItemM2 = property;
                     break;
                  case 3:
                     propertysItemM3 = property;
               }
            }
    
            if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) {
               propertysItemM1 = propertysItemM0;
               propertysItemM2 = propertysItemM0;
               propertysItemM3 = propertysItemM0;
            }
    
            ModificationInfo[] mods = new ModificationInfo[4];
            mods[0] = new ModificationInfo(id + "_m0", priceM0, rangM0);
            mods[0].propertys = propertysItemM0;
            mods[1] = new ModificationInfo(id + "_m1", priceM1, rangM1);
            mods[1].propertys = propertysItemM1;
            mods[2] = new ModificationInfo(id + "_m2", priceM2, rangM2);
            mods[2].propertys = propertysItemM2;
            mods[3] = new ModificationInfo(id + "_m3", priceM3, rangM3);
            mods[3].propertys = propertysItemM3;
            boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item");
            boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted");
            boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item");
            items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, priceM1, rangM1, priceM0, rangM0, mods, specialItem, 0, addable, multicounted));
            ++index;
            if (typeItem == ItemType.COLOR) {
               ColormapsFactory.addColormap(id + "_m0", new Colormap() {
                  {
                     PropertyItem[] var5;
                     int var4 = (var5 = mods[0].propertys).length;
    
                     for(int var3 = 0; var3 < var4; ++var3) {
                        PropertyItem _property = var5[var3];
                        this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", "")));
                     }
    
                  }
               });
            }
         }
      } catch (ParseException var29) {
         var29.printStackTrace();
      }
    

    } как сделать чтобы можно было добавить 1 модификацию для определнных предметов, а для других к примеру все 4 модификации чтобы все работало без ошибок

  2. Assistant

    Для того чтобы добавить только 1 модификацию для определенных предметов и все 4 модификации для других предметов, вам нужно изменить цикл, который создает массив модификаций.

    Вместо использования фиксированного значения 4 в строке for(int m = 0; m < countModification; ++m), вы можете использовать переменную countModification и задать ей значение в зависимости от типа предмета.

    Например, для определенных предметов, где вы хотите добавить только 1 модификацию, вы можете установить countModification равным 1 перед циклом for:

    countModification = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : 1;
    

    Таким образом, цикл будет выполняться только один раз для этих предметов и создаст только одну модификацию.

    Для других предметов, где вы хотите добавить все 4 модификации, оставьте значение countModification равным 4, как в оригинальном коде.

    После этого вы можете удалить часть кода, где значения модификаций присваиваются propertysItemM1, propertysItemM2 и propertysItemM3. Вместо этого присвойте значения propertysItemM1, propertysItemM2 и propertysItemM3 равными propertysItemM0 для предметов, где countModification равно 1, используя условную проверку:

    if (countModification == 1) {
       propertysItemM1 = propertysItemM0;
       propertysItemM2 = propertysItemM0;
       propertysItemM3 = propertysItemM0;
    }
    

    Теперь у вас будет возможность добавлять как 1 модификацию, так и 4 модификации для разных типов предметов без ошибок.

  3. User

    покажи как в коде выглядеть должно

  4. Assistant

    Вот примеризмененного кода, который позволит добавить только 1 модификацию для определенных предметов и все 4 модификации для других предметов:

    private static void parseAndInitItems(String json, ItemType typeItem) {
       JSONParser parser = new JSONParser();
    
       try {
          Object obj = parser.parse(json);
          JSONObject jparser = (JSONObject)obj;
          JSONArray jarray = (JSONArray)jparser.get("items");
    
          for(int i = 0; i < jarray.size(); ++i) {
             JSONObject item = (JSONObject)jarray.get(i);
             LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en"));
             LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en"));
             String id = (String)item.get("id");
             int priceM0 = Integer.parseInt((String)item.get("price_m0"));
             int priceM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m1")) : priceM0;
             int priceM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m2")) : priceM0;
             int priceM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m3")) : priceM0;
             int rangM0 = Integer.parseInt((String)item.get("rang_m0"));
             int rangM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m1")) : rangM0;
             int rangM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m2")) : rangM0;
             int rangM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m3")) : rangM0;
             PropertyItem[] propertysItemM0 = null;
             PropertyItem[] propertysItemM1 = null;
             PropertyItem[] propertysItemM2 = null;
             PropertyItem[] propertysItemM3 = null;
             int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications"));
    
             if (countModification == 1) {
                JSONArray propertys = (JSONArray)item.get("propertys_m0");
                PropertyItem[] property = new PropertyItem[propertys.size()];
    
                for(int p = 0; p < propertys.size(); ++p) {
                   JSONObject prop = (JSONObject)propertys.get(p);
                   property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value"));
                }
    
                propertysItemM0 = property;
                propertysItemM1 = propertysItemM0;
                propertysItemM2 = propertysItemM0;
                propertysItemM3 = propertysItemM0;
             } else {
                for(int m = 0; m < countModification; ++m) {
                   JSONArray propertys = (JSONArray)item.get("propertys_m" + m);
                   PropertyItem[] property = new PropertyItem[propertys.size()];
    
                   for(int p = 0; p < propertys.size(); ++p) {
                      JSONObject prop = (JSONObject)propertys.get(p);
                      property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value"));
                   }
    
                   switch(m) {
                      case 0:
                         propertysItemM0 = property;
                         break;
                      case 1:
                         propertysItemM1 = property;
                         break;
                      case 2:
                         propertysItemM2 = property;
                         break;
                      case 3:
                         propertysItemM3 = property;
                         break;
                   }
                }
             }
    
             ModificationInfo[] mods = new ModificationInfo[4];
             mods[0] = new ModificationInfo(id + "_m0", priceM0, rangM0);
             mods[0].propertys = propertysItemM0;
             mods[1] = new ModificationInfo(id + "_m1", priceM1, rangM1);
             mods[1].propertys = propertysItemM1;
             mods[2] = new ModificationInfo(id + "_m2", priceM2, rangM2);
             mods[2].propertys = propertysItemM2;
             mods[3] = new ModificationInfo(id + "_m3", priceM3, rangM3);
             mods[3].propertys = propertysItemM3;
             boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item");
             boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted");
             boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item");
             items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, priceM1, rangM1, priceM0, rangM0, mods, specialItem, 0, addable, multicounted));
             ++index;
             if (typeItem == ItemType.COLOR) {
                ColormapsFactory.addColormap(id + "_m0", new Colormap() {
                   {
                      PropertyItem[] var5;
                      int var4 = (var5 = mods[0].propertys).length;
    
                      for(int var3 = 0; var3 < var4; ++var3) {
                         PropertyItem _property = var5[var3];
                         this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", "")));
                      }
                   }
                });
             }
          }
       } catch (ParseException var29) {
          var29.printStackTrace();
       }
    }
    

    Примечание: Убедитесь, что вы правильно определили и инициализировали переменные countModification, propertysItemM0, propertysItemM1, propertysItemM2 и propertysItemM3 в вашем коде и использовали их в соответствующих частях кода.

  5. User

    switch(m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } ошибкатут в m

  6. Assistant

    Извините за ошибку - в данной секции кода действительно есть ошибка.

    Используя оператор switch, каждый case блок должен заканчиваться оператором break, чтобы прервать выполнение switch-блока. Ошибка возникает из-за отсутствия оператора break после каждого case.

    Вот исправленный фрагмент кода:

    switch(m) {
       case 0:
          propertysItemM0 = property;
          break;
       case 1:
          propertysItemM1 = property;
          break;
       case 2:
          propertysItemM2 = property;
          break;
       case 3:
          propertysItemM3 = property;
          break;
       default: 
          // Если значение m не совпадает ни с одним из case, можно выполнить некоторые дополнительные действия, если требуется.
          break;
    }
    

    Важно добавить оператор default для обработки сценариев, когда значение m не совпадает с ни одним из case. Это означает, что если значение countModification больше 3 (или меньше 0), будет использоваться default блок или блок не будет выполнен вообще.

    Если у вас возникнут дополнительные вопросы, пожалуйста, сообщите.

  7. User

    вот тут ошибка switch(m) в буквк m

  8. Assistant

    Извините за предыдущую путаницу. Вы правы, ошибка в использовании переменной m в операторе switch. Переменная m имеет тип int, поэтому использование m в качестве выражения в операторе case является недопустимым.

    Вместо этого вы можете использовать значение m внутри оператора case, чтобы сопоставить ветку case со значением m.

    Вот исправленный фрагмент кода:

    switch(countModification) {
       case 1:
          // Логика для предметов с 1 модификацией
          propertysItemM0 = property;
          propertysItemM1 = propertysItemM0;
          propertysItemM2 = propertysItemM0