CPSC 124, Fall 2005
Answers to Quiz #3
Question 1: Explain the meaning of the access modifiers public and private.
Answer: These access modifiers can be applied to a subroutine definition or to the declaration of a member variable. A "public" variable or subroutine can be accessed from outside the class where it is defined. A "private" variable or subroutine can only be accessed in the class where it is defined.
Question 2: Explain what is meant by the term precondition, as it relates to this course.
Answer: A precondition is something that must be true when a subroutine is called, in order for that subroutine to perform correctly. A precondition is an obligation on the part of the caller of the subroutine.
Question 3: Suppose that the first line of a subroutine definition is: static void test(int n, double x). Explain why the statement test(17,42) is a legal subroutine call statement while test(0.17,3.227) is not.
Answer: A formal parameter in a subroutine definition can be replaced in a subroutine call statement by any expression that could be legally assigned (in an assignment statement) to the formal parameter. In test(17,42), 42 is an int, which can legally be assigned to the parameter x of type double. (The computer will automatically convert int to double.) In test(0.17,3.227), 0.17 is of type double while the formal parameter n is of type int, and it is not legal to assign double to int.
Question 4: Briefly explain what is meant by bottom-up design.
Answer: In bottom-up design, the programmer begins by writing some low-level subroutines that perform subtasks that will be useful in the solution of the overall problem (or, better yet, by obtaining pre-written subroutines that perform those subtasks). These subroutines can then be combined into routines that perform higher-level tasks, and then the new routines can be further combined, and so on, until eventually the overall problem is solved.
Part 2: Write a complete subroutine named countSpaces that has one parameter of type String and a return value of type int. The return value should be equal to the number of spaces in the string (that is, the number of characters in the string that are equal to ' '.
Answer: Here is one possible answer:
static int countSpaces( String str ) { int count; // for counting the spaces int pos; // for accessing the positions in the string count = 0; // initialize counter for ( pos = 0; pos < str.length(); pos++ ) if ( str.charAt(pos) == ' ' ) count++; // found a space, so count it } return count; // return the answer }