0

我是 Java 新手。我想解析这种格式的数据

苹果;芒果;橙子:1234;橙子:1244;...;

在任何时间点都可能有多个“橙色”。数字 (1,2...) 增加并相应地作为“橙色”。

好的。拆分后,假设我已将前两个数据(Apple,Orange)存储在一个变量(在 setter 中)以在 getter 函数中返回相同的数据。现在我想将“橙色”事物中的值(1234,1244....等)添加到变量中以便稍后返回。在此之前,我必须检查有多少橙子来了。为此,我知道我必须使用 for 循环。但不知道如何将“值”存储到变量中。

请帮帮我。

4

2 回答 2

0

让我尝试通过我如何解释这个问题以及——更重要的是——它如何关注输入和输出(期望)而不是实际实现来重新表述这个问题:

我需要解析字符串

"Apple;Mango;Orange:1234;Orange:1244;...;"

在某种程度上,我可以检索':'与水果相关的值(之后的数字):

  • 在示例中,我应该收到AppleMango的空列表,因为它们没有价值;
  • 我应该收到一份橙色1234, 1244的清单的清单。

当然,您的直觉HashMap是正确的,但是如果您不太了解具体细节,那么总有人会提出更好的解决方案。

剩下几个白点:

  • 没有值的水果应该有一个默认值吗?
  • 没有价值的水果应该在地图上吗?
  • 输入错误应该如何处理?
  • 应该如何处理重复值?

鉴于这种情况,我们可以开始编写代码:

import java.util.*;

public class FruitMarker {

  public static void main(String[] args) {
    String input = "Apple;Mango;Orange:1234;Orange:1244";
    // replace with parameter processing from 'args'

    // avoid direct implementations in variable definitions
    // also observe the naming referring to the function of the variable
    Map<String, Collection<Integer>> fruitIds = new HashMap<String, Collection<Integer>>();

    // iterate through items by splitting
    for (String item : input.split(";")) {
      String[] fruitAndId = item.split(":"); // this will return the same item in an array, if separator is not found
      String fruitName = fruitAndId[0];
      boolean hasValue = fruitAndId.length > 1;

      Collection<Integer> values = fruitIds.get(fruitName);
      // if we are accessing the key for the first time, we have to set its value
      if (values == null) {
        values = new ArrayList<Integer>(); // here I can use concrete implementation
        fruitIds.put(fruitName, values);   // be sure to put it back in the map
      }
      if (hasValue) {
        int fruitValue = Integer.parseInt(fruitAndId[1]);
        values.add(fruitValue);
      }
    }

    // display the entries in table iteratively
    for (Map.Entry<String, Collection<Integer>> entry : fruitIds.entrySet()) {
      System.out.println(entry.getKey() + " => " + entry.getValue());
    }
  }

}

如果执行此代码,您将获得以下输出:

Mango => []
Apple => []
Orange => [1234, 1244]
于 2012-11-30T16:24:14.557 回答
0
 String input = "Apple;Mango;Orange:1234;Orange:1244;...;"
 String values[] = input.split(";");
 String value1 = values[0];
 String value2 = values[1];

 Hashmap< String, ArrayList<String> > map = new HashMap<String, ArrayList<String>>();
 for(int i = 2; i < values.length; i = i + 2){
      String key = values[i];
      String id = values[i+1];

      if (map.get(key) == null){
          map.put(key, new ArrayList<String>());
      }
      map.get(key).add(id);
 }

 //for any key s:
  // get the values of s
  map.get(s);  // returns a list of all values added
  // get the count of s
  map.get(s).size(); // return the total number of values. 
于 2012-11-30T14:53:11.453 回答