I have a boolean method as following below
public boolean validID(String personalNumber) { .... }
I wanna to print out a string "is valid" or "is not valid" dependent on if the boolean true or false.
the problem is how can I print out string in a boolean method. The code below return always false even if the if statment is true.
if (sum % 10 == 0) {
return Boolean.parseBoolean("is valid");
} else {
return false;
}
You have only two choices :
a boolean
method :
public boolean validID(String personalNumber) { // ... code to compute 'sum' return sum % 10 == 0; }
a String
method :
public String validID(String personalNumber) { // ... code to compute 'sum' if (sum % 10 == 0) { return personalNumber + " is valid"; } else { return personalNumber + " is not valid"; } }
Or a choice that combine both, the String
one that calls the boolean
one :
public boolean isValidId(String personalNumber) {
// ... code to compute 'sum'
return sum % 10 == 0;
}
public String validID(String personalNumber) {
if (isValidId(personalNumber)) {
return personalNumber + " is valid";
} else {
return personalNumber + " is not valid";
}
}
I'd suggest to take the boolean
one, the better is to let the method find the validity of the personalNumber
and let the code that calls it handle the result to print a message, because you may this method again and this time you'll need the boolean result to handle it differently
String id = "fs6d7f6sd";
if(this.validID(id))
System.out.println("ID is valid");
else
System.out.println("ID is not valid");
I recommend to use bean Result
. Check my code.
class Result {
private boolean value;
private String message;
public Result(boolean value, String message) {
this.value = value;
this.message = message;
}
// getter & setter
}
public Result validID(String number) {
// ... code to compute 'sum'
return sum % 10 == 0 ?
new Result(true, "valid") :
new Result(false, "invalid");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.