Lecture 9 - Example class Flashcards
1
Q
Write a recursive algorithm which takes an int n and prints a row of asterisks of length n.
A
Here we can return the String or just print either works.
- Stopping criteria is n equals 0 print nothing and return else
- The recursive method, a method calling itself repeatedly.
2
Q
Write a recursive algorithm that takes a string s and writes the characters vertically
A
Recursion must have 1., a stopping case and 2., a recursive method where the method is calling itself.
In this case, we can return the String or print it. Both work.
- Stopping criteria is when there is if the length of the String =s. (Note: we can’t say look for the last point in the string because each time the method is called it doesn’t know that there was a char already printed out and that it is a substring)
- The recursive method is to print the first character and call the vertical substring.
3
Q
When might you get a java.lang.StackOverflowError
A
When the method has been called so many times that it has ran out of space in memory.
This would happen when there is no stopping case.
4
Q
How do you write lines from a file in reverse order?
A
public class ReverseFile extends ConsoleProgram { public void run() { println("This program reverses the lines in a file."); BufferedReader rd = openFileReader("Enter input file: "); String[] lines = readLineArray(rd); for (int i = lines.length - 1; i >= 0; i--) { println(lines[i]); }