Recursion and File Handling in Java, Exams of Computer Science

Various questions related to recursion and file handling in java. It includes questions on recursive methods for finding the greatest common divisor, bubble sort recursive, finding the nth largest distinct value in an array, creating exception classes, summing digits in a string, reversing words in a string, copying selections to a file, and creating classes with properties, constructors, and interfaces. The document also includes a question on creating a campus class with an array of building objects and a clone method.

Typology: Exams

Pre 2010

Uploaded on 09/17/2009

koofers-user-kas-1
koofers-user-kas-1 🇺🇸

10 documents

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
The exam is worth 100 points (although 110 points are available) and it has 11 questions. Unless
other constraints are given, you may use any classes or methods from the Java API in your solutions.
You may create helper methods as necessary. You may leave only toString and accessor methods out of
your class solutions. If you find them necessary, include them.
Use the following code to answer Questions 1 and 2.
public static int method( int num1, int num2 ) {
int result = num1;
if (num2 > 0) {
result = method(num2, num1 % num2);
}
return result;
}
1. [6 pts] State the base case(s), recursive case(s), recursive step(s) utilized in method.
base case: num2 <= 0
recursive case: num2 > 0
recursive step: result = method(num2, num1 % num2);
2. [8 pts] Step through the call method(66, 24), showing each state that develops as you move into
and back out of the recursion.
num1 = 66, num2 = 24
result = method(66, 24) Remark:
num1 = 24, num2 = 18
result = method(24, 18) 66%24 = 18
num1 = 18, num2 = 6
result = method(18, 6) 24%18 = 6
num1 = 6, num2 = 0
result = method(6, 0) num2 == 0 so it reaches the base case.
result = num1 = 6
return result = 6 since 18%6 = 0, i.e. num2==0 & num1=6
return result = 6
return result = 6
return result = 6
return result = 6
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Recursion and File Handling in Java and more Exams Computer Science in PDF only on Docsity!

The exam is worth 100 points (although 110 points are available) and it has 11 questions. Unless

other constraints are given, you may use any classes or methods from the Java API in your solutions.

You may create helper methods as necessary. You may leave only toString and accessor methods out of

your class solutions. If you find them necessary, include them.

Use the following code to answer Questions 1 and 2.

public static int method( int num1, int num2 ) { int result = num1; if (num2 > 0) { result = method(num2, num1 % num2); } return result; }

1. [6 pts] State the base case(s), recursive case(s), recursive step(s) utilized in method.

base case: num2 <= 0 recursive case: num2 > 0 recursive step: result = method(num2, num1 % num2);

2. [8 pts] Step through the call method(66, 24), showing each state that develops as you move into

and back out of the recursion.

num1 = 66, num2 = 24

result = method(66, 24) Remark: num1 = 24, num2 = 18 result = method(24, 18) 66%24 = 18 num1 = 18, num2 = 6 result = method(18, 6) 24%18 = 6 num1 = 6, num2 = 0 result = method(6, 0) num2 == 0 so it reaches the base case. result = num1 = 6 return result = 6 since 18%6 = 0, i.e. num2==0 & num1= return result = 6 return result = 6 return result = 6 return result = 6

3. [10 pts] Create a recursive solution to the method bubbleSortRecursive( Comparator list[] ).

Your solution must show the implementation of the bubble sort algorithm.

public static void bubbleSortRecursive( Comparator list[] ) { bubbleSortRecursiveOuterLoop( list, list.length1 ); } private static void bubbleSortRecursiveOuterLoop( Comparator list[], int i ) { if ( i > 0 ) { bubbleSortRecursiveInnerLoop( list, 1, i ); bubbleSortRecursiveOuterLoop( list, i1 ); } } private static void bubbleSortRecursiveInnerLoop( Comparator list[], int i, int iUntil ) { int prev = i1; if ( i <= iUntil ) { if ( list[i].compare( list[prev], list[i] ) > 0 ) { // Swap if list[i] is greater list[next] Comparator temp = list[i]; list[i] = list[prev]; list[prev] = temp; } bubbleSortRecursiveInnerLoop( list, i+1, iUntil ); }

5. [8 pts] Create the class NonNumericCharacterException. The class will represent a value which

should contain only digits, but erroneously contains other characters as well. For a complete

context of usage, read the following question before beginning your solution.

class NonNumericCharacterException extends Exception { private String errString; private char errChar; public NonNumericCharacterException() { super(); } public NonNumericCharacterException( String msg ) { super( msg ); } public NonNumericCharacterException( String eS, char eC ) { super(); errString = eS; errChar = eC; } }

6. [10 pts] Create a method sumDigits(String value). The method will sum the individual digits

within value. Recall the method public static boolean isDigit( char digit) is within the class

Character. Incorporate the usage of the exception class created above in your solution.

public static int sumDigits( String value ) throws NonNumericCharacterException { int sum = 0; for ( int i = 0; i < value.length(); ++i ) { if ( Character.isDigit( value.charAt( i ) ) ) { sum += Integer.parseInt( value.substring( i, i+1 ) ); } else { //throw new NonNumericCharacterException(); //throw new NonNumericCharacterException( value + // " contains at least one nondigit character. " ); throw new NonNumericCharacterException( value, value.charAt( i ) ); } } return sum;

7. [10 pts] Create the method String reverseWords(String s). The method will receive a string,

recursively reversing the order of the words contained in the string. Return the new string.

Assume that the input string is only composed of letters and single blank spaces separating

groups of letters (words). The string will not contain other white space and will not contain

punctuation. If s = “I am a gator”, then reverseWords( s ) will return “gator a am I”.

public static String reverseWords( String s ) { return reverseWordsRecursively( s, s.length()2, s.length()1 ); } private static String reverseWordsRecursively( String s, int leftIndex, int rightIndex ) { // A Base Case if ( rightIndex < 0 ) { return ""; } // A Base Case if ( leftIndex < 0 && s.charAt( rightIndex ) != ' ' ) { return s.substring( 0, rightIndex+1 ); } // A Recursive Case else if ( s.charAt( rightIndex ) == ' ' ) { return s.substring( rightIndex, rightIndex+1 ) + reverseWordsRecursively( s, rightIndex2, rightIndex1 ); } // A Base Case else if ( leftIndex == 0 ) { return s.substring( leftIndex, rightIndex+1 ); } // A Recursive Case else if ( s.charAt( leftIndex ) == ' ' ) { return s.substring( leftIndex+1, rightIndex+1 ) + reverseWordsRecursively( s, leftIndex1, leftIndex ); } // A Recursive Case else { return reverseWordsRecursively( s, leftIndex1, rightIndex ); } }

8. [8 pts] State the base case(s), recursive case(s), and recursive step(s) utilized in your solution to

reverseWords. Also, discuss how your solution is leading you from the start to the base case.

The base cases and recursive cases are shown in the code above. The recursive steps are inside the recursive cases. The program traverses the string from the highest index to the lowest index and extract a word from the string whenever it encounters a white space. It stops and extracts the last word when it has traversed to the start of the string. Each extracted word is added to the end of the return

9. [14 pts] Create the method copySelectionsToFile. The method will receive three strings. The

first two being String names of the desired input and output files from the current directory. The

final parameter is a string value to locate within the input file. Write to the output file any line

of the input file which contains the value. The method will not return anything. A sample input

file and output file is given here. The value is “gator”.

Input file given:

I am a gator

I am a from florida

go gators!

go florida!

Output file result:

I am a gator

go gators!

public static void copySelectionsToFile( String inFile, String outFile, String value ) { BufferedReader in = null; BufferedWriter out = null; try { // Open Files in = new BufferedReader( new FileReader( inFile ) ); out = new BufferedWriter( new FileWriter( outFile ) ); // Copy Values from Read File to Write File String line = null; while ( (line = in.readLine()) != null ) { boolean isFound = false; for ( int i = 0; i < line.length() value.length() + 1; ++i ) { if ( !isFound ) { for ( int j = 0; j < value.length(); ++j ) { if ( line.charAt( i+j ) != value.charAt( j ) ) { j = value.length(); // break from the inner loop } else if ( j == value.length() 1 ) { isFound = true; } } } } if ( isFound ) { out.write( line ); out.newLine(); } } // Close Files in.close(); out.close(); } catch ( IOException e ) { System.out.println( "IOException Error(s)!" ); }

10. [16 pts] Create the class Building. The class will contain two properties, name type String, the

name of the building, and stories type int, the number of stories (floors) in the building. The

class will implement the interfaces Comparable (comparisons based upon the stories in the

building), Comparator (comparisons based upon the name of the building), and Cloneable.

class Building implements Comparable, Comparator, Cloneable { // Properties private String name; private int stories; // Constructors public Building() { name = new String( "unknown" ); stories = 1; } public Building( String _name, int _stories ) { name = _name; stories = _stories; } // Clone Method public Object clone() { return new Building( new String( name ), stories ); } // Method from Comparable public int compareTo( Object obj ) { // comparisons based upon the stories return stories ((Building)obj).stories; } // Methods from Comparator public int compare( Object obj1, Object obj2 ) { // comparisons based upon the name return ((Building)obj1).name.compareTo( ((Building)obj2).name ); } public boolean equals( Object obj1, Object obj2 ) { // comparisons based upon the name return ((Building)obj1).name.compareTo( ((Building)obj2).name ) == 0; }