How do I get toString () to return a multiline string?

I am working on a program that loops through an array and finds the smallest value and then prints the time, firstName and lastName for the runner.

I need to figure out how to return three values ​​on separate lines, for example:

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

      

What i have right now

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

+3


source to share


4 answers


try it



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

      

0


source


String.format("%s%n%s%n%s", firstName, lastName, Time); 

      

if you are using format use format string with arguments.



  • %s

    = String
  • %n

    = new line
+3


source


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

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

      

+1


source


The newline depends on the OS being defined System.getProperty("line.separator");

So:

public String toString() {
       String myEol = System.getProperty("line.separator");  
       return String.format( firstName + myEol +  lastName + myEol + Time);
}

      

+1


source







All Articles