Java中的break语句
我用 Java 编写了一个“setX”方法,它表示如果 x 值 ( (x,y) ) 为负数,则 x 的值不会改变,并且 main() 将照常继续。
void setX (int num)
{
if (num < 0)
break;
else
{
_x = num;
}
}
我说得对吗? 由于break问题,我不确定break语句是否只是从当前方法中中断?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
break
仅在循环(while、for)中使用。如果您想退出该方法,请使用
return
代替。break
is used only in loops (while, for).If you want to exit the method, use
return
instead.也许你的意思是
Perhaps you meant
你应该使用
return
。break
是打破循环。you should use
return
.break
is to break loops.此处使用
return;
。break
用于跳出循环。Use
return;
here.break
is used to break out of loops.根据 Java 教程, break 与
switch
、for
、while
和do
-while
循环。它不会出现在 if 语句中。对于switch
来说,break
可以防止switch
掉入下一个case
,否则它会发生这种情况。对于循环,无论循环防护如何,它都会停止循环。break
语句可以是无标签的,在这种情况下,它会转到switch
或循环之后控制通常恢复的位置,也可以是带标签的,在这种情况下,它会转到标签(几乎就好像它是一个对其来源有严格限制的goto
)。要退出当前方法,请使用
return
。没有值的返回是离开void
方法的正确语句。According to the Java tutorial, break is for use with
switch
,for
,while
, anddo
-while
loops. It doesn't go in if statements. For aswitch
thebreak
keeps theswitch
from falling through to the nextcase
, 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 theswitch
or loop, or labeled, in which case it goes to the label (almost as if it were agoto
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 avoid
method.看起来应该可行,但无论如何,休息确实没有做任何事情。为什么不只是 if(num>=0) _x = num;
That looks like it should work, but the break really isn't doing anything anyway. why not just if(num>=0) _x = num;
我想如果你的逻辑反过来的话,你的意图可能会更清楚一些;
I think your intention might be a bit clearer if your logic was reversed;