在没有system.out.println的情况下在poop中输出字符串

时间:2013-11-03 22:21:14

标签: java oop methods

我试图从方法中的对象类输出我的详细信息,并且我记得使用类似于此

的方法
 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;

我认为我们正在使用某种字符串构建器,当我返回输出时如何输出所有这些

2 个答案:

答案 0 :(得分: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();

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

答案 1 :(得分:1)

所以你想使用StringBuilder? (JavaDoc

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

等...