[英]Return True or false inside a method
假设我有一个方法,我想用这个方法返回真或假。我应该声明布尔值,但我不知道如何。你能帮我解决这个问题吗?我该怎么做?我在我的方法中传递对象参数和我使用的每个参数。我想使用这个对象的名字、姓氏和金钱,如果钱大于 50 将返回 true,如果它小于 100。在另一种情况下,此方法将返回 false。
public static int trueorfalse(String on,String surname,double money,double cost){
if(get.money>50.0 && get.cost<100.0){
System.out.println("Money is"+money);
System.out.println("Name and accepted"+on);
System.out.println("Surname and accepted"+surname);
y=true;
}
else
{
System.out.println("Money is"+money);
System.out.println("Name and denied"+on);
System.out.println("Surname and denied"+surname);
y=false;
}
return y;
}
将返回类型从int
更改为boolean
。 那是,
public static int trueorfalse(String on,String surname,double money,double cost)
至
public static boolean trueorfalse(String on,String surname,double money,double cost)
您可以稍微简化一下,例如
public static boolean trueorfalse(String on, String surname,
double money, double cost) {
boolean accepted = get.money > 50.0 && get.cost < 100.0;
String msg = accepted ? "accepted" : "denied";
System.out.printf("Money is %.2f%n", money);
System.out.printf("Name and %s %s%n", msg, on);
System.out.printf("Surname and %s %s%n", msg, surname);
return accepted;
}
您方法的当前返回类型为int
因此您的方法只能返回int
。
如果要让方法返回boolean
类型值,即true
或false
,则需要将方法的返回类型从int
更改为boolean
public static boolean trueorfalse(String on,String surname,double money,double cost)
{
//content
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.