0

我试图从我的对象类中以一种方法输出我的详细信息,我记得使用过类似的方法

 String output;
     output = "Name: " + this.Name;
     output = "Address: " + this.Address;
     output = "Balance: " + this.balance;
     output = "Minutes used" + this.minutes;
     output = "Texts Sent: " + this.texts;
     output = "Cost per Minute: " + this.unitMinuteCost;
     output = "Cost per Text: " + this.unitTextCost;


     return output;

我想我们正在使用某种字符串生成器当我返回输出时如何输出所有这些

4

2 回答 2

2

您可以开始连接这些String值,例如...

 String output;
 output = "Name: " + this.Name;
 output += "Address: " + this.Address;
 output += "Balance: " + this.balance;
 output += "Minutes used" + this.minutes;
 output += "Texts Sent: " + this.texts;
 output += "Cost per Minute: " + this.unitMinuteCost;
 output += "Cost per Text: " + this.unitTextCost;

或者您可以StringBuilder用于相同的任务

StringBuilder output = new StringBuilder(128);
output.append("Name: ").append(this.Name);
output.append("Address: ").append(this.Address);
output.append("Balance: ").append(this.balance);
output.append("Minutes used").append(this.minutes);
output.append("Texts Sent: ").append(this.texts);
output.append("Cost per Minute: ").append(this.unitMinuteCost);
output.append("Cost per Text: ").append(this.unitTextCost);

return output.toString();

但编译器会自动为您执行此操作。如果您在循环中创建输出,则建议使用 a StringBuilder,因为编译器本身无法进行这种优化

于 2013-11-03T22:22:30.160 回答
1

所以你想用StringBuilder?( JavaDoc )

StringBuilder output = new StringBuilder();
output.append("Name: ").append(this.Name);
output.append("Address: ").append(this.Address);

ETC...

于 2013-11-03T22:25:44.563 回答