Java 如何使用 System.out.println 打印方法的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2219565/
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 to print the result of a method with System.out.println
提问by Terry
How do I print out the result of a method? I want to print out the return of translate but it displays true or false. Suggestions please.
如何打印出方法的结果?我想打印出 translate 的返回,但它显示 true 或 false。请提出建议。
/**
* @returns the string "yes" if "true" and "no" if false
*/
public String translate(boolean trueOrFalse)
{
if(pback == true)
{
return "yes";
}
else
{
return "no";
}
}
/**
* Display book info
*/
public void displaybook()
{
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("ISBN: " + isbn);
System.out.println("Pages: " + pages);
System.out.println("Paperback: " + pback);
System.out.println("Suggested Price: " + price);
}
回答by Jim Ferrans
System.out.println("Paperback: " + translate(pback));
回答by Marius
public void displaybook()
{
System.out.println("Paperback: " + translate(pback));
}
回答by Athens Holloway
It looks like you mistakenly concatenated your variable pback
instead of the result of your translate method in the following statement:
看起来您pback
在以下语句中错误地连接了变量而不是 translate 方法的结果:
System.out.println("Paperback: " + pback);
Instead, replace that statement with
相反,将该语句替换为
System.out.println("Paperback: " + translate(pback));
回答by Adeel Ansari
Please don't forget to call the method, since you wrote it for some reason, I guess.
请不要忘记调用该方法,因为我猜您是出于某种原因编写的。
System.out.println("Paperback: " + translate(pback));
Now, few suggestions, do yourself a favour and change the method like below. if(pback == true)
, makes no sense. See, The Test of Truth, for your amusement.
现在,一些建议,帮自己一个忙,改变如下方法。if(pback == true)
, 没有意义。看,真理的考验,为了你的娱乐。
public String translate(boolean pback) {
return pback ? "yes" : "no";
}
Well, if you don't like ternary, do this,
好吧,如果你不喜欢三元,就这样做,
public String translate(boolean pback) {
if(pback) return "yes";
else return "no";
}
If you like braces, put braces there,
如果你喜欢大括号,把大括号放在那里,
public String translate(boolean pback) {
if(pback) {
return "yes";
} else {
return "no";
}
}
If you don't like 2 return statements, do this,
如果您不喜欢 2 个 return 语句,请执行此操作,
public String translate(boolean pback) {
String yesNo;
if(pback) {
yesNo = "yes";
} else {
yesNo = "no";
}
return yesNo;
}
回答by finnw
public String translate(boolean trueOrFalse) {
if(pback == true) ...
Should probably be:
应该是:
public String translate(boolean trueOrFalse) {
if(trueOrFalse) ...