Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java程序解析字符串并获取字符数_Java_String_Parsing - Fatal编程技术网

Java程序解析字符串并获取字符数

Java程序解析字符串并获取字符数,java,string,parsing,Java,String,Parsing,我应该写一个程序来解析分子,并得到原子数。 这样地: C6H12OH,输出应为C=6,O=1,H=13 这是我迄今为止编写的代码: class ParseMolecule { public static void main(String s[]) { System.out.println("The atoms count in the molecule C6H12OH is :" + getElementsMap("C6H12OH")); }

我应该写一个程序来解析分子,并得到原子数。 这样地: C6H12OH,输出应为C=6,O=1,H=13

这是我迄今为止编写的代码:

class ParseMolecule 
{ 
    public static void main(String s[])
    {
        System.out.println("The atoms count in the molecule C6H12OH is :" + getElementsMap("C6H12OH"));
    }

    public static Map<String, Integer> getElementsMap(String molecule) 
    {
        for(char c : molecule.toCharArray())
        {
            System.out.println(c);
        }
    }
}

这不是我的家庭作业什么的。我刚刚在一个网站上发现了这一点,我正在尝试解决它。

您可以从以下工作开始,仅适用于由单个字符表示的元素:

   String input = "C6H12OH";
   Pattern p = Pattern.compile("([A-Z])([0-9]*)");
   Matcher m = p.matcher(input);
   Map <Character, Integer> atoms = new HashMap<Character, Integer>();
   while (m.find()) {
       Character element = m.group(1).charAt(0);
       Integer count =  Integer.parseInt(m.group(2).equals("") ? "1" : m.group(2));
       atoms.put(element, count + (atoms.get(element) == null ? 0 : atoms.get(element)));
   }
   System.out.println(atoms);
伪代码:

char last = 0
for (char c: input)
  if (!isDecimal(c))
    if (count == 0) // no number between 2 characters
      count = 1
    map[last] += count
    last = c
    count = 0
  else
    count = count*10 + charToInt(c)
    last = 0

你需要表现出更多的努力,这就是你学习的方式——通过思考。如果我们为你写程序,我们就剥夺了你的经验。我会是你的朋友。一个好的开始就是想办法手工完成,然后开始实施。它可能不会为您提供最优雅的解决方案,但它会为您提供一个在学习过程中可以改进的解决方案。public static Map getElementsMapString molecule{int num[]=new int[10];char ch[]=new char[12];forint i=0;i