Java中的break语句

发布于 2024-11-02 14:12:53 字数 286 浏览 6 评论 0原文

我用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

三生池水覆流年 2024-11-09 14:12:53

break 仅在循环(while、for)中使用。

如果您想退出该方法,请使用 return 代替。

break is used only in loops (while, for).

If you want to exit the method, use return instead.

且行且努力 2024-11-09 14:12:53

也许你的意思是

public void setX(int x) {
   if (x >= 0)
        _x = x; 
}

Perhaps you meant

public void setX(int x) {
   if (x >= 0)
        _x = x; 
}
眼泪也成诗 2024-11-09 14:12:53

你应该使用returnbreak 是打破循环。

you should use return. break is to break loops.

陈甜 2024-11-09 14:12:53

此处使用 return;break 用于跳出循环。

Use return; here. break is used to break out of loops.

吐个泡泡 2024-11-09 14:12:53

根据 Java 教程, breakswitchforwhiledo-while 循环。它不会出现在 if 语句中。对于 switch 来说,break 可以防止 switch 掉入下一个 case,否则它会发生这种情况。对于循环,无论循环防护如何,它都会停止循环。

break 语句可以是无标签的,在这种情况下,它会转到 switch 或循环之后控制通常恢复的位置,也可以是带标签的,在这种情况下,它会转到标签(几乎就好像它是一个对其来源有严格限制的goto)。

要退出当前方法,请使用return。没有值的返回是离开 void 方法的正确语句。

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.

孤寂小茶 2024-11-09 14:12:53

看起来应该可行,但无论如何,休息确实没有做任何事情。为什么不只是 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;

不气馁 2024-11-09 14:12:53

我想如果你的逻辑反过来的话,你的意图可能会更清楚一些;

void setX (int num)
{
    if (num >= 0)
        _x = num;
}

I think your intention might be a bit clearer if your logic was reversed;

void setX (int num)
{
    if (num >= 0)
        _x = num;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文