Reputation: 1546
I wrote a 'setX' method in Java that says that if x value ( (x,y) ) is negative, the value of x wont be change, and the main() will continue as usual.
void setX (int num)
{
if (num < 0)
break;
else
{
_x = num;
}
}
Am I right ? I am not sure because of the break issue, is the break statement just break from the current method ?
thnx
Upvotes: 0
Views: 2376
Reputation: 5222
I think your intention might be a bit clearer if your logic was reversed;
void setX (int num)
{
if (num >= 0)
_x = num;
}
Upvotes: 0
Reputation: 4443
That looks like it should work, but the break really isn't doing anything anyway. why not just if(num>=0) _x = num;
Upvotes: 0
Reputation: 533500
Perhaps you meant
public void setX(int x) {
if (x >= 0)
_x = x;
}
Upvotes: 3
Reputation: 14766
According to the Java tutorial, break is for use with switch
, for
, while
, and do
-while
loops. It doesn't go in if statements. For a switch
the break
keeps the switch
from falling through to the next case
, which it would otherwise do. For loops it stops looping regardless of the loop guards.
A break
statement can either be unlabeled, in which case it goes to where control would normally resume after the switch
or loop, or labeled, in which case it goes to the label (almost as if it were a goto
with strict constraints on where it can come from).
To get out of the current method, use return
. A return with no value is the proper statement to leave a void
method.
Upvotes: 0
Reputation: 37945
break
is used only in loops (while, for).
If you want to exit the method, use return
instead.
Upvotes: 10