Skip to main content

Learning about Code Structure

Section 1.9 Rule 1) Conjoining Conditions

Continue watching the video to learn when to conjoin conditions with ||; and answer the following questions.
Figure 1.9.1. Conjoining conditions with || part 4

Activity 1.9.1.

There is a copy of the following code block in interactive mode that you can compile. Your task is to improve the code’s style as an expert would view it, while ensuring its behavior remains unchanged. You may run your refactored code to verify that it still passes all test cases.
public class Internship { 
	public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
		if (schoolYear >= 4) {
			if (GPA >= 3.5) {
		    	if (hasWorkExperience) {
		        	return "Eligible";
		    	} else {
		        	return "You only need some work experience!";
		    	}
			}
		}
		return "Not eligible";
	}
}

Activity 1.9.2.

    Which of the following code blocks is the most similar to your final refactored code for the previous question?
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear >= 4 && GPA >= 3.5 && hasWorkExperience) {
          return "Eligible";
        } else {
          return "You only need some work experience!";
        }
        return "Not eligible";
      }
    }
    
  • This code does not compile because the last return statement in unreachable (never executes).
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear >= 4 && GPA >= 3.5 && hasWorkExperience) {
          return "Eligible";
        }
        return "Not eligible";
      }
    }
    
  • The code doesn’t have the same functionality with the original one.
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear < 4 || GPA < 3.5) {
          return "Not eligible";
        }
        if (hasWorkExperience) {
          return "Eligible";
        }
        return "You only need some work experience!";
      }
    }
    
  • You did it correctly!
  • public class Internship {
      public static String checkInternshipEligibility(int schoolYear, double GPA, boolean hasWorkExperience) {
        if (schoolYear >= 4 && GPA >= 3.5) {
          if (hasWorkExperience) {
            return "Eligible";
          } else {
            return "You only need some work experience!";
          }
        }
      return "Not eligible";
      }
    }
    
  • This code has nested ifs and can be improved further!
You have attempted 1 of 4 activities on this page.