How can I have toString() return a multi-line string?

半腔热情 提交于 2019-12-04 10:53:51
prashant thakre

Try This

public String toString(){ return String.format( firstName + ".%n " + lastName + ".%n " + Time);
String.format("%s%n%s%n%s", firstName, lastName, Time); 

if you are using format then use the format string with arguments.

  • %s = String
  • %n = new line

To print them on different lines, you need to add a "line break", which is either "\n" or "\r\n" depends on the Operating System you are on.

public String toString(){
    return String.format( firstName + "\n" +  lastName + "\n" + Time);

A new line depends on OS which is defined by System.getProperty("line.separator");

So:

public String toString() {
       String myEol = System.getProperty("line.separator");  
       return String.format( firstName + myEol +  lastName + myEol + Time);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!