i was wondering if its possible for method to be the condition in if else statements.
i have a method called takephoto(). if takephoto() was successfully done it will do another method.
i did it this way
if (takephoto() == true)
{
anothermethod();
}
i get an error that says
The operator == is undefined for the argument type(s) void, boolean
for the line
if (takephoto() == true)
this is my takephoto()method
public static void takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
}
}
The method takephoto should return boolean, not void (i.e. nothing).
Then the answer is yes, but you should write it like this:
if (takephoto()) {
// do something
}
Your version will work too but this one is simpler and cleaner.
If takephoto() returns a boolean, that return value is itself the condition for your if statement, so you can write it as:
if (takephoto()) {
...
}
You'll have to make your takephoto() return a boolean, not a void value.
---- EDIT ----
public static boolean takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
return true;
}
else
return false;
}
if (takephoto()) {
}
public boolean takephoto()
{
return true; //or false
}
Yes, you can do this but your takephoto() method should return either true or false.
public static boolean takephoto(){
//if the code was successful
return true;
}
Or return false if picture was unsuccessful.
Here's how you could fix it:
public static boolean takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
return true;
}
else{
return false;
}
}
You say "if takephoto() was successfully done it will do another method." You have to have a way for takephoto to indicate if it was successful. The way you do that is to return a boolean.
yes, you can, but if statement checks between two parameters of same type.
your if statement:
if (takephoto())
{
///if takephoto() true
anothermethod();
}
your takephoto method:
public static boolean takePhoto() {
if(camera != null) {
camera.takePicture(null, null, pictureTakenHandler);
return true;
}
return false;
}
Related
Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean in the correct way.
public Space fire()
{
System.out.println("Hi");
}
public boolean hitRateAnalysis()
{
if (HitShipPercentage < 50 && Shots!=0)
return true;
else{
return false;
}
}
Your fire() is wrong and will cause a compilation error, you have to return an instance of Space. Either change the return type of the method to void or return an instance of the Space class.
This will call the fire method correctly:
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots != 0){
fire();
return true;
}
return false;
}
Your code has a few errors in it, the fire() method is of type Space which means it's supposed to return a Space. I don't think this is what you want, my guess is fire isn't supposed to return anything in which case it should be void.
public void fire() {
System.out.println("Hi");
}
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots!=0) {
fire();
return true;
}
return false;
}
I don't understand why I am getting "return statement missing".
Here is the image with the code:
In your 2nd and 3rd if conditions there are no returns. Instead of your else, just return false.
So it reads:
public class isTrans {
public static boolean isTrans(String s,String t) {
if (t.length()==1 && (s.charAt(s.length()-1))==t.charAt(0)){
return true;
} else if (s.charAt(0)==t.charAt(0)){
return isTrans(s,t.substring(1));
} else if (s.charAt(1)==t.charAt(1)){
return isTrans(s,t.substring(1), t);
}
return false;
}
}
In this case you have to return in all the conditions or return at the end of the method.
if(/*...*/) {
return true;
}
else if(/*...*/) {
return isTrans(/*...*/); // return whatever isTrans returns
}
else if(/*...*/) {
return isTrans(/*...*/); // here too
}
else {
return false;
}
You have to return the result of the function execution in your else if, so the recursion works properly. Like this:
return isTrans(s, t.substring(1))
I've been researching how to return a random boolean and then use that returned boolean to drive an "if" statement, but I can't figure out how to structure or what syntax to use.
private Random random;
public void mousePressed(MouseEvent e) {
determineHit();
if (random = true) {
//Perform true//
}
else {
//Perform false//
}
private boolean determineHit() {
return random.nextBoolean();
}
How can I get my determineHit method to return the boolean and then plug that back into the main body of the method?
Thanks
private Random random;
public void mousePressed(MouseEvent e) {
boolean hitResult = determineHit();
if (hitResult) {
//Perform true//
}
else {
//Perform false//
}
private boolean determineHit() {
return random.nextBoolean();
}
Since an if () requires a boolean result, the == true is implied, no need to explicitly code it.
Just make sure that you have instantiated random before using it, in a constructor for example.
if (random.nextBoolean()) {
//Perform true//
} else {
//Perform false//
}
I need to compare two Objects. If there is a difference I need to log it corresponding to particular difference and return the true.
For example:
private boolean compTwoObjects(Object objA, Object ObjB) {
if(objA.getType() != objB.getType()) {
logTheDifference("getType is differing");
return true;
}
.
.
.
// Now this could invoke other composite methods
if(checkFont(objA.getFont(), objB.getFont()) {
logTheDifference("Font is differing");
return true;
}
}
private boolean checkFont(Font fontObjA, Font fontObjB) {
if(fontObjA.getBold() != fontObjB.getBold()) {
logTheDifference("font bold formatting differs");
return true;
}
.
.
.
if(fontObjA.getAllCaps() != fontObjB.getAllCaps()) {
logTheDifference("font all caps formatting differs");
return true;
}
.
.
.
if(checkBorderDiff(fontObjA.getBorder(), fontObjB.getBorder())) {
logTheDifference("border diff");
return true;
}
}
private boolean checkBorderDiff(Border borderObjA, Border borderObjB) {
if (borderObjA.getColor() != null || borderObjB.getColor() != null) {
if (!borderObjA.getColor().equals(borderObjB.getColor())) {
logIt("border color differing");
return true;
}
}
if (borderObjA.getDistanceFromText() != borderObjB.getDistanceFromText()) {
logIt("distance of the border from text or from the page edge in points differing");
return true;
}
if (borderObjA.isVisible() != borderObjB.isVisible()) {
logIt("border visibility differing");
return true;
}
if (borderObjA.getLineStyle() != borderObjB.getLineStyle()) {
logIt("line style differing for border");
return true;
}
if (borderObjA.getLineWidth() != borderObjB.getLineWidth()) {
logIt("border width in points differing");
return true;
}
if (borderObjA.getShadow() != borderObjB.getShadow()) {
logIt("border shadow differing");
return true;
}
}
//And it is going like this.
My problem is I want to avoid multiple if statements in the methods. Also I want to log the messages corresponding to particular difference.
I have read few similar type of problems on stackoverflow solved either by command pattern or HashMap. But they don't include comparisons in that.
I want to refactor my code to get rid of series of if's.
Have a system of comparators, backed by generics. Every comparer will also know what is next in line. For example:
interface IComparer<T> {
boolean areDifferent (T first, T second);
}
class FontComparer implements IComparer<Font> {
#Override
public boolean areDifferent(Font first, Font second) {
// Compare fonts start
// ..
// Compare fonts end
return new BorderComparer().areDifferent(first.getBorder(), second.getBorder());
}
}
class BorderComparer implements IComparer<Border> {
#Override
public boolean areDifferent(Border first, Border second) {
//Do border comparison alone
return false;
}
}
You could setup a comparer chain now, and bail out when comparison fails. Otherwise, comparison goes to the comparer next in the chain.
The client code will finally look like:
Object one = new Object();
Object two = new Object();
new ObjectComparer().areDifferent(one, two);
Have you considered enums?
private enum FontCmp {
Bold {
#Override
boolean cmp(Font a, Font b) {
return a.getBold() != b.getBold();
}
},
AllCaps {
#Override
boolean cmp(Font a, Font b) {
return a.getAllCaps() != b.getAllCaps();
}
},
Border {
#Override
boolean cmp(Font a, Font b) {
return BorderCmp.compare(a.getBorder(), b.getBorder());
}
};
// Each enum has one of these.
abstract boolean cmp(Font a, Font b);
// Compare them all and log any failures.
static boolean compare(Font a, Font b) {
for (FontCmp c : FontCmp.values()) {
if (c.cmp(a, b)) {
logIt("FontCmp-" + c + " failed");
return false;
}
}
return true;
}
}
You could also use reflection as described here. Also look into introspection as described here
Fundamentally you are trying to do a series of comparisons, so there is little choice but to do a series of comparisons.
What you could do is define an interface/enum/abstract class which is a FieldChecker. That FieldChecker would have an abstract method implemented differently in each FieldChecker:
String performCheck(Font a, Font b) {
if (DO CHECK HERE) {
return "failure message";
}
return null;
}
Then your check function just becomes:
for (FieldChecker fc: fieldCheckers) {
String res = fc.performCheck(a,b);
if (res != null) {
return res;
}
}
return "All ok";
I need help on how to return a boolean method in java. This is the sample code:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}
else {
addNewUser();
}
return //what?
}
I want the verifyPwd() to return a value on either true or false whenever I want to call that method. I want to call that method like this:
if (verifyPwd()==true){
//do task
}
else {
//do task
}
How to set the value for that method?
You're allowed to have more than one return statement, so it's legal to write
if (some_condition) {
return true;
}
return false;
It's also unnecessary to compare boolean values to true or false, so you can write
if (verifyPwd()) {
// do_task
}
Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.
boolean success = true;
if (some_condition) {
// Handle the condition.
success = false;
} else if (some_other_condition) {
// Handle the other condition.
success = false;
}
if (another_condition) {
// Handle the third condition.
}
// Do some more critical things.
return success;
try this:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
return true;
}
}
if (verifyPwd()==true){
addNewUser();
}
else {
// passwords do not match
System.out.println("password do not match");
}
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
addNewUser();
return true;
}
}
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
Best way would be to declare Boolean variable within the code block and return it at end of code, like this:
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
I find this the best way.