繁体   English   中英

从键列表Java获取整数值

[英]Get integer value from key list java

我有一个如下的json文件:

[
    {
        "100": "2"
    },
    {
        "50": "5"
    },
    {
        "30": "3"
    },
    {
        "10": "8"
    },
    {
        "5": "4"
    }
]

解析之后,我可以得到密钥:

public static void main(String[] args, int value)
    {
        JSONParser parser = new JSONParser();

            try {
                JSONArray jsonArray = 
                        (JSONArray) parser.parse(
                                new FileReader("/Users/.../Documents/workspace/testCase/bin/test.json"));

                int remaining = value;
                for (int n = 0 ; n < jsonArray.size(); n++)
                {
                    JSONObject note = (JSONObject)jsonArray.get(n);
                    Set keys = note.keySet();
                    int result = Math.floor(remaining/keys);
                    }

            }
    }

如何从键集中提取键作为整数,以便可以使用int numOfChange = Math.floor(remaining/keys); 操作?

我不确定这是否是您的意思,但是据我了解,

当您从文件中获取一个字符串时,为了将它们视为整数,您必须对它们进行解析,例如

int a = Integer.parseInt(string);

如果要保留相同的内衬,则可能会读取一行的两个字符串,并将它们保存在HashMap中,就像解析的第一个字符串保存为键,第二个字符串保存为值一样

Integer.parseInt方法需要使用String作为参数,因为您有一个集合,因此需要遍历元素。 例如:

for(String s : keys){
  System.out.println(Integer.parseInt(s));
}

注意:以下实现基于注释中的问题:

问题 :给定Set作为参数,可以通过将String转换为Integer返回Set

public Set<Intege> StringSetToIntegerSet(Set<String> input) throws Exception{
   Set<Integer> output=new HashSet<Integer>();
   for(String s : input){
      output.add(Integer.parseInt(s));
   }
   return output;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM