Java Reference
In-Depth Information
18.13
Show the call stack for isPalindrome("abcba") using the method defined in
Listing 18.4.
Check
Point
18.14
Show the call stack for selectionSort(new double[]{2, 3, 5, 1}) using the
method defined in Listing 18.5.
18.15
What is a recursive helper method?
18.6 Case Study: Finding the Directory Size
Recursive methods are efficient for solving problems with recursive structures.
Key
Point
The preceding examples can easily be solved without using recursion. This section presents a
problem that is difficult to solve without using recursion. The problem is to find the size of a
directory. The size of a directory is the sum of the sizes of all files in the directory. A directory
d may contain subdirectories. Suppose a directory contains files f 1 , f 2 , c , f m and subdirec-
tories d 1 , d 2 , c , d n , as shown in Figure 18.5.
VideoNote
Directory size
directory
f 1
f 2
. . .
f m
d 1
d 2
d n
. . .
F IGURE 18.5
A directory contains files and subdirectories.
The size of the directory can be defined recursively as follows:
size ( d n )
The File class, introduced in Section 12.10, can be used to represent a file or a directory and
obtain the properties for files and directories. Two methods in the File class are useful for
this problem:
size ( d )
=
size ( f 1 )
+
size ( f 2 )
+ c +
size ( f m )
+
size ( d 1 )
+
size ( d 2 )
+ c +
The length() method returns the size of a file.
The listFiles() method returns an array of File objects under a directory.
Listing 18.7 gives a program that prompts the user to enter a directory or a file and displays
its size.
L ISTING 18.7
DirectorySize.java
1 import java.io.File;
2 import java.util.Scanner;
3
4 public class DirectorySize {
5 public static void main(String[] args) {
6 // Prompt the user to enter a directory or a file
7 System.out.print( "Enter a directory or a file: " );
8 Scanner input = new Scanner(System.in);
9 String directory = input.nextLine();
10
11 // Display the size
12 System.out.println(getSize( new File(directory)) + " bytes" );
13 }
invoke method
 
 
 
Search WWH ::




Custom Search