java 如何让 toString() 返回多行字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26491801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I have toString() return a multi-line string?
提问by Supernaturalgirl 1967
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?
有没有办法将三个值打印在不同的行上?
采纳答案by prashant thakre
Try This
试试这个
public String toString(){ return String.format( firstName + ".%n " + lastName + ".%n " + Time);
回答by Leonard Brünings
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
%s
= 字符串%n
= 新行
回答by user1032613
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.
要将它们打印在不同的行上,您需要添加一个“换行符”,“\n”或“\r\n”取决于您使用的操作系统。
public String toString(){
return String.format( firstName + "\n" + lastName + "\n" + Time);
回答by Dan
A new line depends on OS which is defined by System.getProperty("line.separator");
新行取决于由以下定义的操作系统 System.getProperty("line.separator");
So:
所以:
public String toString() {
String myEol = System.getProperty("line.separator");
return String.format( firstName + myEol + lastName + myEol + Time);
}