首页 > 解决方案 > 没有进入forloop内部

问题描述

我正在尝试为电话拨号盘创建一个号码关联映射,如下所示:

private Integer[][] dialpad = { {1   , 2   , 3},
                                {4   , 5   , 6},
                                {7   , 8   , 9},
                                {null, 0   , null} };

现在,根据 的规则关联:

1 should 2,4,5
2 should be 1,3,4,5,6
3 should be 2,5,6
and so on............

我已经编写了代码来处理这个问题:

public void createDialAssociation()
{
    int nosCols = dialpad[0].length;
    int nosRows = dialpad.length;
    //int rowFrom, rowTo, colFrom, colTo;

    for(int row=0; row<nosRows; row++)
    {
        for(int col=0; col<nosCols; col++)
        {
            Integer currentElement = dialpad[row][col];
            elementAssociation.put( currentElement, new ArrayList<Integer>());

            int rowFrom =  (row-1)< 0 ? 0 : (row-1);
            int rowTo = (row+1) <= (nosRows-1)? row+1: nosRows-1;
            int colFrom = (col-1)<0 ? 0 : (col-1);
            int colTo = (col+1) <= (nosCols-1) ? col+1 : nosCols-1;

            LOG.info("row,col,element = " + row + "," +col+ ","+ currentElement);
            LOG.info("rowFrom = " + rowFrom);
            LOG.info("rowTo = " + rowTo);
            LOG.info("colFrom = " + colFrom);
            LOG.info("colTo = " + colTo);
            LOG.info("---------------------------------------------------- " );
            for(int currentRowIndex=rowFrom; currentRowIndex==rowTo; currentRowIndex++)
            {
                LOG.info("1..............");
                for(int currentColIndex = colFrom; currentColIndex == colTo ; currentColIndex++)
                {
                    LOG.info("2..............");
                    if ( currentRowIndex == row || currentColIndex == col )
                        continue;

                    if( dialpad[currentRowIndex][currentColIndex] != null)
                    {
                        elementAssociation.get(currentElement).add(dialpad[currentRowIndex][currentColIndex]);
                    }

                }
            }

        }
    }

我的问题是,代码没有进入循环:

for(int currentRowIndex=rowFrom; currentRowIndex==rowTo; currentRowIndex++)

因此,我没有看到

LOG.info("1.......);
or LOG.info("2........);

我可以期待任何见解/帮助吗?

标签: java

解决方案


for(int currentRowIndex=rowFrom; currentRowIndex==rowTo; currentRowIndex++){}

初始化currentRowIndex为 的值rowFrom。虽然currentRowIndex==rowTo它运行循环的内容并在每次执行循环后运行currentRowIndex++。因此,循环最多恰好在 时进入一次rowFrom==rowTo

您可能希望继续循环直到currentRowIndex==rowTo,甚至可能包括这种情况。这意味着您必须在rowFrom仍低于时运行 continue 循环rowTo,因此您必须编写rowFrom<rowToor rowFrom<=rowTo

您的内部循环也是如此。


推荐阅读