物事を理解しやすくし、よりオブジェクト指向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