![]() |
![]() |
|
This is a sample exam, based on a previous semester. Although it represents most of the major topics we've covered, it doesn't necessarily cover everything that will be on this semester's exam.
Instructions:static boolean | inDaylightTime( String country, int year, int month, int day )
Determine whether the given date is in daylight savings time, for the given country. |
which takes in anisFrabjous
aloha, and store the result in the variable you declared in (a):
catheterhas
catas a prefix, and also
catheterhas
caas a prefix, but
catheterdoes not have
cathyas a prefix.
static void testHasPrefix() { System.out.println( "Actual : " + hasPrefix( "professor", "pro" ) ); System.out.println( "Desired: " + true ); System.out.println( "Actual : " + hasPrefix( "pro", "professor" ); System.out.println( "Desired: " + false ); System.out.println( "Actual : " + hasPrefix( "prof", "prof") ); System.out.println( "Desired: " + true ); } |
hint: When callingsubstring , be sure that the indices you provide aren't bigger than the length of the string you're extracting the substring from!
// (b) Signature here static boolean hasPrefix ( String s1 , |
Mr.or
Dr., nothing else), and some don't. You need to write a function which takes in the entire name as one
Dr.or
Mr.. For example, here are some test cases your code must pass:
static void testAddTitleIfNeeded() { System.out.println( "Actual : " + addTitleIfNeeded( "Mr. Oscar Grouch" ) ); System.out.println( "Desired: " + "Mr. Oscar Grouch" ); // no need to add title System.out.println( "Actual : " + addTitleIfNeeded( "Dr. B. Burner" ) ); System.out.println( "Desired: " + "Dr. B. Burner" ); // no need to add title System.out.println( "Actual : " + addTitleIfNeeded( "Big Bird" ) ); System.out.println( "Desired: " + "Mr. Big Bird" ); // NEED to add title System.out.println( "Actual : " + addTitleIfNeeded( "T" ) ); System.out.println( "Desired: " + "Mr. T" ); // NEED to add title } |
Below, write the signature (2pts) and body (5pts) for
static String addTitleIfNeeded( String name ) {
if (hasPrefix(name,"Mr. ") || hasPrefix(name,"Dr. ")) {
return name; // make no changes
}
else {
return "Mr. " + name;
}
}
|
Note that there are other ways to write this function as well,
but using
and codify Mr.
as the standard title,
you could re-factor the above to:
String addTitleIfNeeded( String name ) { final String STD_TITLE = "Mr. "; String additionalTitle; if (hasPrefix(name,STD_TITLE) || hasPrefix(name,"Dr. ")) { additionalTitle = ""; } else { additionalTitle = STD_TITLE; } return additionalTitle + name; } |
instead of a country-name. Also, in real lifeLocale
This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |