为了使事情更容易理解和更面向对象,我认为使用Compound
您自己的类可能会按需要工作。
class Compound {
String last;
String compound;
int lastSuffixCount;
Compound() {
this.last = "";
this.compound = "";
this.lastSuffixCount = 0;
}
public String getCompound() {
return compound;
}
public void setCompound(String compound) {
this.compound = compound;
}
public void add(String suffix, int times) {
if (suffix.equals(this.last) && times > 0)
{
this.compound = compound.replace(lastSuffixCount + "", "");
this.lastSuffixCount = lastSuffixCount + times;
this.compound += lastSuffixCount;
} else if (times > 0) {
this.compound += suffix + times;
}
this.lastSuffixCount = times;
this.last = suffix;
}
}
示例驱动程序:
public static void main(String[] args) {
Compound c = new Compound();
c.add("H", 2);
System.out.println(c.getCompound());
c.add("H", 1);
System.out.println(c.getCompound());
c.add("O", 6);
c.add("H", 4);
System.out.println(c.getCompound());
}
输出:
H2
H3
H3O6H4