无法删除 StringBuffer 字符串的最后一个字符

Cannot delete last char of StringBuffer String

我面临一个奇怪的(对我来说)问题,即无法删除字符串缓冲区字符串的最后一个字符。我正在构建一个应用程序,其中有很多复选框,我想获取多个值,这就是为什么我使用 stringbuffer 来附加复选框名称的原因。

代码:

int length = iceCreamPreference.length();
                if (length>0){
                    iceCreamPreference = iceCreamPreference.deleteCharAt(length - 1);
                }
                Toast.makeText(SweetsLayoutActivity.this,
                        "Quantity: " + quantityNumberFinal +
                                "\nIce Cream Flavors: " + iceCreamPreference.toString() +
                                "\nIce Scream Scoops: " + quantityIceCreamNumberFinal +
                                "\nSyrups: " + syrupPreference.toString(), Toast.LENGTH_LONG).show();

我在哪里构建 StringBuffer:

private void checkWhatIceCreamSelected() {
        iceCreamPreference = new StringBuffer();
        if (chocolate.isChecked()){
            iceCreamPreference.append(chocolate.getText().toString() + ", ");
        }
        if (strawberry.isChecked()){
            iceCreamPreference.append(strawberry.getText().toString() + ", ");
        }
        if (vanilla.isChecked()){
            iceCreamPreference.append(vanilla.getText().toString() + ", ");
        }
        if (banana.isChecked()){
            iceCreamPreference.append(banana.getText().toString() + ", ");
        }
        if (cookies.isChecked()){
            iceCreamPreference.append(cookies.getText().toString() + ", ");
        }
        if (pistachio.isChecked()){
            iceCreamPreference.append(pistachio.getText().toString() + ", ");
        }
        if (cheeseCake.isChecked()){
            iceCreamPreference.append(cheeseCake.getText().toString() + ", ");
        }
        if (oreo.isChecked()){
            iceCreamPreference.append(oreo.getText().toString() + ", ");
        }
        if (mango.isChecked()){
            iceCreamPreference.append(mango.getText().toString() + ", ");
        }
        if (caramel.isChecked()){
            iceCreamPreference.append(caramel.getText().toString() + ", ");
        }
        if (pineapple.isChecked()){
            iceCreamPreference.append(pineapple.getText().toString() + ", ");
        }
        if (sorbet.isChecked()){
            iceCreamPreference.append(sorbet.getText().toString() + ", ");
        }


    }

结果:

HERE

我想删除最后一个“,”逗号。

任何建议将不胜感激!!!

StringBuffer 中的最后一个字符将是 space,因此您需要删除最后两个字符以去掉最后的逗号。

您可以在名称前使用逗号并放置一个逻辑,这样它就不会在第一个数据输入前附加逗号。所以代码将是

声明一个布尔变量

 boolean comma=false;

然后执行如下代码

    private void checkWhatIceCreamSelected() {
    iceCreamPreference = new StringBuffer();



    if (chocolate.isChecked()){
        if(comma!=false)
        {
        iceCreamPreference.append( ", ");
        }
        iceCreamPreference.append(chocolate.getText().toString());
        comma=true;
    }
      //do same for all other if 

}