我面临着一个奇怪的(对我来说)无法删除stringbuffer字符串的最后一个字符的问题。我正在构建一个应用程序,其中我有许多复选框,我想采取多个值,这就是为什么我使用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() + ", ");
}
}
结果:
我想拥有最后一个","逗号删除了。
任何建议都将受到高度赞赏!!!
答案 0 :(得分:0)
StringBuffer中的最后一个字符将是一个空格,因此您需要删除最后两个字符以删除最后一个逗号。
答案 1 :(得分:0)
您可以在名称前使用逗号并输入逻辑,以便在首次输入数据之前不附加逗号。所以代码将是
声明一个布尔变量
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
}