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

旧时模样 提交于 2019-12-06 05:13:38

问题


I'm working on a program that searches through an array and finds the smallest value and then prints out the time, firstName, and lastName of the runner.

What I need to figure out is how to return the three values on separate lines, something like:

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

That's what I have right now

Is there a way to have the three values print out on separate lines?


回答1:


Try This

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



回答2:


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



回答3:


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);



回答4:


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);
}


来源:https://stackoverflow.com/questions/26491801/how-can-i-have-tostring-return-a-multi-line-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!