简体   繁体   English

在方法内返回 True 或 false

[英]Return True or false inside a method

Lets say i have a method and i want to do this method to return true or false.I should declare boolean but i dont know how.Could you help me with this?How can i do it?I pass objects in my methods with the parameteres and each one i use it.I want to use this objects name,surname and money if the money is bigger than 50 will return true and if it is smaller than 100.In another case this method will return false.假设我有一个方法,我想用这个方法返回真或假。我应该声明布尔值,但我不知道如何。你能帮我解决这个问题吗?我该怎么做?我在我的方法中传递对象参数和我使用的每个参数。我想使用这个对象的名字、姓氏和金钱,如果钱大于 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;
}

Change the return type to boolean from int . 将返回类型从int更改为boolean That is, 那是,

public static int trueorfalse(String on,String surname,double money,double cost)

to

public static boolean trueorfalse(String on,String surname,double money,double cost)

You could simplify it a bit, like 可以稍微简化一下,例如

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

Current return-type of your method is int so your method can only return an int . 您方法的当前返回类型为int因此您的方法只能返回int

If you want your method to return a boolean type value,ie, either true or false , you need to change the return-type of your method from int to boolean 如果要让方法返回boolean类型值,即truefalse ,则需要将方法的返回类型从int更改为boolean

public static boolean trueorfalse(String on,String surname,double money,double cost)
{
    //content
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM