...

View Full Version : return value of java method



cwl157
11-24-2004, 02:00 PM
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.

shmoove
11-24-2004, 02:05 PM
You can just call the method in the if statement:


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

cwl157
11-24-2004, 02:09 PM
so if i was gonna put it in a while loop can i say


while (isEven(n))
{
\\do some stuff;
}

shmoove
11-24-2004, 03:29 PM
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

Antoniohawk
11-24-2004, 06:15 PM
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 &&? :)

shmoove
11-24-2004, 07:04 PM
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

Antoniohawk
11-24-2004, 09:30 PM
Oh ok, I understand now. I have never used that method before, I usually just use the modulus operator for that kind of thing.


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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum