Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New Coder
    Join Date
    Jun 2003
    Posts
    92
    Thanks
    0
    Thanked 0 Times in 0 Posts

    return value of java method

    How do i write a statement that checks the return value of a method in java. I have to do a conditional action based on the return value of true or false. How do i put this in an If statement and a while loop.

  • #2
    Regular Coder
    Join Date
    Dec 2003
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You can just call the method in the if statement:
    Code:
    boolean isEven(int number) {
      return (number & 1 == 0);
    }
    
    // ...
    int n;
    // ...
    if (isEven(n)) {
      // do something for even numbers
    }
    else {
      // do something for odd numbers
    }
    shmoove

  • #3
    New Coder
    Join Date
    Jun 2003
    Posts
    92
    Thanks
    0
    Thanked 0 Times in 0 Posts
    so if i was gonna put it in a while loop can i say
    Code:
     
    while (isEven(n))
    {
      \\do some stuff;
    }

  • #4
    Regular Coder
    Join Date
    Dec 2003
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes. The expresions in while and for statements need to evaluate to a boolean reasult. If they don't the compiler will give out an error. If a method returns a boolean value then it indeed evaluates into a boolean result.

    shmoove

  • #5
    Senior Coder
    Join Date
    Aug 2002
    Location
    Kansas City, Kansas
    Posts
    1,518
    Thanks
    0
    Thanked 2 Times in 2 Posts
    Code:
    boolean isEven(int number) {
      return (number & 1 == 0);
    }
    
    // ...
    int n;
    // ...
    if (isEven(n)) {
      // do something for even numbers
    }
    else {
      // do something for odd numbers
    }
    Shouldn't that be &&?

  • #6
    Regular Coder
    Join Date
    Dec 2003
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Nope. It's a bitwise AND, not a logical AND. I'm checking that the least significant bit is 0 (hence the number is even).

    shmoove

  • #7
    Senior Coder
    Join Date
    Aug 2002
    Location
    Kansas City, Kansas
    Posts
    1,518
    Thanks
    0
    Thanked 2 Times in 2 Posts
    Oh ok, I understand now. I have never used that method before, I usually just use the modulus operator for that kind of thing.

    Code:
    if (x % 2 == 0)
      x is true


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •