![]() |
![]() |
|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Note:this page is yet to be fleshed out...
class StringLooper {
/** Return how many occurrences of `target` occur in `s`.
* @param s the string to search through
* @param target the char to count.
* @return how many occurrences of `target` occur in `s`.
*/
int countOccurences( String s, char target ) {
int seenSoFar = 0;
int i=0;
while (i < s.length()) {
if (s.charAt(i) == target) {
seenSoFar = seenSoFar + 1;
}
// else do nothing.
i = i + 1;
}
return seenSoFar;
}
}
|
boolean isValidISBN10( String isbn ) {
return false; // stub.
}
|
int charToInt( char digit ) {
return Integer.parseInt( Character.toString(digit) );
}
|
class StringLooperTester {
public static void main( String[] args ) {
StringLooper looper = new StringLooper();
System.out.println( "\nTest some okay (but contrived) ISBNs: " );
checkExpect( looper.isValidISBN10("0000000000"), true );
checkExpect( looper.isValidISBN10("1000000001"), true );
checkExpect( looper.isValidISBN10("0100000002"), true );
checkExpect( looper.isValidISBN10("0010000003"), true );
checkExpect( looper.isValidISBN10("0001000004"), true );
checkExpect( looper.isValidISBN10("0000000019"), true );
checkExpect( looper.isValidISBN10("0000000027"), true );
checkExpect( looper.isValidISBN10("2000000010"), true );
checkExpect( looper.isValidISBN10("4000000020"), true );
checkExpect( looper.isValidISBN10("5000000080"), true );
System.out.println( "\nTest some real and incorrect ISBNs: " );
checkExpect( looper.isValidISBN10("0306406152"), true );
checkExpect( looper.isValidISBN10("0306406162"), false );
checkExpect( looper.isValidISBN10("0306406154"), false );
checkExpect( looper.isValidISBN10("0553565699"), true );
checkExpect( looper.isValidISBN10("1553565699"), false );
}
static void checkExpect( boolean actual, boolean expected ) {
if (actual == expected) {
System.out.print(".");
}
else {
System.out.println("failed test: expected " + expected + ", got " + actual );
}
}
}
|
Extra challenge: Actually, sometimes the check-digit works out to be 10. Since that won't fit into a single digit, in that case the letter 'X' is used (reminiscent of the roman numeral).
Fix your code above so that ISBN-10s ending in the letter 'X' are also recognized.
System.out.println( "\nTest some X-digit ISBNs: " );
checkExpect( looper.isValidISBN10("000000000X"), false );
checkExpect( looper.isValidISBN10("050000000X"), true );
checkExpect( looper.isValidISBN10("000020000X"), true );
checkExpect( looper.isValidISBN10("300000002X"), true );
|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
| ©2009, Ian Barland, Radford University Last modified 2009.Apr.06 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarland |
![]() |