简体   繁体   中英

Problem with Decrement Operator in While Loop

I'm trying to write a program that calculates the sum of all the numbers in a diagonal section of a multiplication chart (basically from row 12 column 1 of the array to row 1 column 12). The problem is, in the code the Rowcounter refuses to decrease after every loop while the Colcounter increases just fine. What am I doing wrong?

    public Integer  ComputeDiagonalSum(int multiplier)
{
    Integer [][] MultiArray = new Integer[multiplier][multiplier];
    int RowCounter = MultiArray.length - 1;
    int ColCounter = 0;
    Integer DiagonalSum = 0;

    while(RowCounter > 0)
    {
        int RowNumber = RowCounter + 1;
        //
        //Compute inner loop
        while(ColCounter < MultiArray[multiplier - 1].length)
        {
            int ColNumber = ColCounter + 1;
            //Load each box in the current column of the current row
            MultiArray[RowCounter][ColCounter] = RowNumber * ColNumber;
            DiagonalSum += MultiArray[RowCounter][ColCounter];
            ColCounter++;
        }
      //doesn't work
        RowCounter--;
    }
    return DiagonalSum;
}

Link to image of multiplication chart: https://www.google.com/search?client=ms-android-samsung-ga-rev1&sxsrf=ACYBGNQo4QAYAF-MjmvCR4jcbz3RqDx0eg%3A1581776894027&ei=_v9HXvKbAYilUoveveAE&q=multiplication+chart+&oq=multiplication+chart+&gs_l=mobile-gws-wiz-serp.3..35i39j0i22i30.1455.2670..3471...0.0..0.765.1392.5-1j1......0....1.0tdlwHvu690#imgrc=jtyeYkOxpQT3CM :

The issue is not that your RowCounter does not decrease, but that you need to move initialization of ColCounter inside the first loop, at the beginning. The evaluation of while(ColCounter < MultiArray[multiplier - 1].length) will always return false after the first iteration, because ColCounter has reached the size of your array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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