Skip to main content

Practice Code Structure

Section 1.12 Identification

Activity 1.12.1.

    These code blocks are the same as the ones you saw in the previous question, and they all have the same functionality. Among these options which one is preferable?
  • public static void printCompetitionEligibility(boolean hasBuiltRobot, boolean passedSafetyTest, boolean registeredOnTime) {
        if (hasBuiltRobot) {
            if (passedSafetyTest) {
                if (registeredOnTime) {
                    System.out.println("Eligible to join the competition!");
                } else {
                    System.out.println("Not eligible.");
                }
            } else {
                System.out.println("Not eligible.");
            }
        } else {
            System.out.println("Not eligible.");
        }
    }
    
  • This code can be improved!
  • public static void printCompetitionEligibility(boolean hasBuiltRobot, boolean passedSafetyTest, boolean registeredOnTime) {
       if (hasBuiltRobot && passedSafetyTest && registeredOnTime) {
          System.out.println("Eligible to join the competition!");
       } else {
          System.out.println("Not eligible.");
       }
    }
    
  • Correct!
  • public static void printCompetitionEligibility(boolean hasBuiltRobot, boolean passedSafetyTest, boolean registeredOnTime) {
       if (!hasBuiltRobot) { 
          System.out.println("Not eligible.");
       } else if (!passedSafetyTest) {
          System.out.println("Not eligible.");
       } else if (!registeredOnTime) {
          System.out.println("Not eligible.");
       } else {
          System.out.println("Eligible to join the competition!");
       }
    }
    
  • This code can be improved!
You have attempted 1 of 2 activities on this page.