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
Supernaturalgirl 1967
source
to share
4 answers
try it
public String toString(){ return String.format( firstName + ".%n " + lastName + ".%n " + Time);
0
prashant thakre
source
to share
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
Leonard brΓΌnings
source
to share
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
user1032613
source
to share
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
Dan
source
to share