简体   繁体   English

JAVA:替代break语句?

[英]JAVA: Substitute for a break statement?

For some ridiculous reason my professor has prohibited us from using break statements in our programs to terminate loops. 由于某些荒谬的原因,我的教授禁止我们在程序中使用break语句来终止循环。 I am making a Connect Four program and am using for loops to simulate the player dropping a checker. 我正在制作一个“连接四人”程序,并使用for循环来模拟玩家丢下检查器的过程。 If my loops look like this: 如果我的循环如下所示:

for(int i = LOWEST_ROW_INDEX; i >= 0; i--)
    {
        if(gb[i][rChoice].equals(". "))
        {
            gb[i][rChoice] = "r ";
            break; //CANNOT USE BREAK
        }
    }

What could I do instead of a break statement to terminate this for loop? 我可以代替break语句来终止此for循环怎么办?

您可能会作弊:

i = -1;

It's not sooo ridiculous. 这不是那么可笑。 Some purists consider break as being evil - similar to "mutliple return statements", but not as much as " break with label" or goto . 一些纯粹主义者认为break是邪恶的-与“多重return语句”相似,但不及“与标签break ”或goto A program with nested loops and some break statements can be rather confusing. 具有嵌套循环和一些break语句的程序可能会造成混乱。

Another possible solution here would be something like this: 这里的另一个可能的解决方案是这样的:

private int findInsertionIndex()
{
    for(int i = LOWEST_ROW_INDEX; i >= 0; i--)
    {
        if(gb[i][rChoice].equals(". "))
        {
            return i;
        }
    }
    return -1;
}

// Use
int insertionIndex = findInsertionIndex();
if (insertionIndex != -1)
{
    gb[insertionIndex][rChoice] = "r ";
}

(Yes, I know that I traded a break against a method with "multiple returns". Sometimes it's all about playing the game. I think the code snippet already shows some practices that one could consider as worse than a break . For example, odd variable names, global variables and a 2D array of Strings...) (是的,我知道我用一个具有“多重收益”的方法换了一个break 。有时候,这全都与玩游戏有关。我认为代码段已经显示了一些人们认为比break更糟糕的做法。例如,奇怪变量名称,全局变量和2D字符串数组...)

Convert it to while 转换为while

int i = LOWEST_ROW_INDEX;
while(!gb[i][rChoice].equals(". ") && i >=0 ){
  i--;
}
if (i >= 0){
  gb[i][rChoice] = "r ";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM