Skip to content
Advertisement

if statement not working to add 1 based on a condition

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);

Advertisement

Answer

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);
  }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement