Home » Java » java – Using AND OR within a IF statement of a two dimensional array in order sum the value of a row-Exceptionshub

java – Using AND OR within a IF statement of a two dimensional array in order sum the value of a row-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I would like to sum the value of the first row of a 4×5 two dimensional array and put into the int variable rowTotal1. Each object within the array has both a value and a name. If the sum of values exceeds 21 for the row AND if any of the cells within the row have any of these four names (“AA”, “AB”, “AC”, “AD”), I’d like like to subtract 10 from the total row sum. Below is what I have so far but it is not able to subtract 10 under the right circumstances

    for(int i=0; i<5; i++) {
        rowTotal1 += square[0][i].value;
            if(rowTotal1 > 22 && square[0][i].name == "AA" ||
                                 square[0][i].name == "AB" ||
                                 square[0][i].name == "AC" ||
                                 square[0][i].name == "AD") {
                rowTotal1 += square[0][i].value - 10;
            }
    }
How to&Answers:

Do you mean:

let rowTotal1 = 0;
let hasSpecialNames = false;

for(int i=0; i<5; i++) {
  rowTotal1 += square[0][i].value;

  if (square[0][i].name == "AA" ||
                       square[0][i].name == "AB" ||
                       square[0][i].name == "AC" ||
                       square[0][i].name == "AD") {
    hasSpecialNames = true;
  }
}

if(rowTotal1 > 21 || hasSpecialNames) {
  rowTotal1 = rowTotal1 - 10;
}

Answer:

First,

values exceeds 21

but you write

if(rowTotal1 > 22...

shouldn’t it be rowTotal1 > 21?

About you question,

rowTotal1 += square[0][i].value – 10;

What is the value for square[0][i].value?

If you want to “subtract 10 from the row”,

just rowTotal1 -= 10; should do it.