Home > Software design >  if statement not working to add 1 based on a condition
if statement not working to add 1 based on a condition

Time:10-07

This code determines the wins and losses of each quarter but I am having trouble with the PerfectQuarter. A PerfectQuarter is described as when one team has 0 points in a quarter but the other team scores.
Everything runs fine but when I enter scores for each quarter and put 00-01 for quarter one, the print statement at the end of my program prints

PerfectQuarters: 0

for both teams, although Team 2 should have a perfect quarter of 1 since in QuarterOne they scored once and Team 1 scored 0 points.

         if (teamOneQuarterOne > teamTwoQuarterOne) {
         teamOneStats  = "W-";
         teamTwoStats  = "L-";

         if (teamOneQuarterOne == 0 && teamTwoQuarterOne > 0) {
             teamTwoPerfectQuarter  ;        }
     } else if (teamTwoQuarterOne < teamOneQuarterOne) {
         teamOneStats  = "L-";
         teamTwoStats  = "W-";

         if (teamTwoQuarterOne == 0 && teamOneQuarterOne > 0) {
             teamOnePerfectQuarter  ;   }
     } else if (teamOneQuarterOne < teamTwoQuarterOne) {
         teamOneStats  = "L-";
         teamTwoStats  = "W-";

     } else {
         teamOneStats  = "T-";
         teamTwoStats  = "T-";        }

System.out.println(teamOne   " Perfect Quarters: "   teamOnePerfectQuarter);
     System.out.println(teamTwo    " Perfect Quarters: "    teamTwoPerfectQuarter);

CodePudding user response:

It seems that you expect these lines to increase the perfect count.

if (teamOneQuarterOne == 0 && teamTwoQuarterOne > 0) {
             teamTwoPerfectQuarter  ;        }

But these lines are only relevant if the enveloping condition is true

if (teamOneQuarterOne > teamTwoQuarterOne)

But both cannot be true together at the same time.

It seems that you have misplaced those lines, I'd expect them in here:

if (teamOneQuarterOne < teamTwoQuarterOne) {
         teamOneStats  = "L-";
         teamTwoStats  = "W-";
         /* here */
     }

CodePudding user response:

Try to divide "comparing" conditions and "check perfect" conditions in two separate if-else branches

class Example {
  public void main(String[] args) {
    if (teamOneQuarterOne > teamTwoQuarterOne) {
      teamOneStats  = "W-";
      teamTwoStats  = "L-";
    } else if (teamOneQuarterOne < teamTwoQuarterOne) {
      teamOneStats  = "L-";
      teamTwoStats  = "W-";
    } else {
      teamOneStats  = "T-";
      teamTwoStats  = "T-";
    }

    if (teamOneQuarterOne == 0 && teamTwoQuarterOne > 0) {
      teamTwoPerfectQuarter  ;
    } else if (teamTwoQuarterOne == 0 && teamOneQuarterOne > 0) {
      teamOnePerfectQuarter  ;
    }
    System.out.println(teamOne   " Perfect Quarters: "   teamOnePerfectQuarter);
    System.out.println(teamTwo   " Perfect Quarters: "   teamTwoPerfectQuarter);
  }
}
  •  Tags:  
  • java
  • Related