可以在for循环中使用不等于吗?

huangapple go评论61阅读模式
英文:

Can I nUse not equal for for loop

问题

抱歉提出一个新手问题。

假设我要在一个方法中使用for循环,并且当满足条件时我需要跳出循环。

那么我可以在for循环中使用不等于吗,就像这样:

代码

String p;

if (p.equals("snake")) {
    break;
} else {
    for (int i = 0; i != break; i++) {
        System.out.println("请输入您最喜欢的宠物:");
        p = ent.nextString();
    }
}

代码

英文:

Sorry to ask a newbie question.

Let say I am to use for loop for a method and I need to break out when the condition is met.

So can I use not equal in the for loop like

Code

String p;

If(p = snake){
Break;}
Else
{
For(I=0; I != break; I++){
System.out.println(“Please enter your favourite pet: ”);
P = ent.nextString();
}
}

code

答案1

得分: 1

以下是翻译好的内容:

从技术上讲,您是可以的,但对于这种情况,可以使用 while 循环:

while (!conditionToBreak) {
    // 做一些事情

    if (shouldBreak()) {
        conditionToBreak = true;
    }
}

关于这个循环(以及类似的 do-while 循环),您可以在这里阅读更多信息。


另外 - 请检查您的代码,因为在当前状态下它不会工作 - 例如 I != break 是错误的,因为 break 是一个关键字。

英文:

Technically you can but for such situation there is a while loop

while(!conditionToBreak) {
    // do something

    if(shouldBreak()) {
        conditionToBreak = true;
    }
}

About this loop (and similar do-while) you can read more here


Also - review your code because in current state it will not work - e.g. I != break is wrong because break is a keyword

huangapple
  • 本文由 发表于 2020年9月10日 15:53:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63825196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定