Supernaturalgirl 1967
Supernaturalgirl 1967

Reputation: 289

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

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?

Upvotes: 6

Views: 19662

Answers (4)

prashant thakre
prashant thakre

Reputation: 5147

Try This

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

Upvotes: 0

Leonard Brünings
Leonard Brünings

Reputation: 13242

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

Upvotes: 8

Dan
Dan

Reputation: 876

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

Upvotes: 3

WSBT
WSBT

Reputation: 36373

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

Upvotes: 1

Related Questions