In: Computer Science
Problem Description:
Write a program that prompts the user to enter a directory and displays the number of the files in the directory.
Analysis:
(Describe the problem including input and output in your own words.)
Design:
(Describe the major steps for solving the problem. How do you use recursion to solve this problem.)
Coding: (Copy and Paste Source Code here. Format your code using Courier 10pts)
Name the public class Exercise18_29
Testing: (Describe how you test this program)
Answer) **No specific coding language mentioned, hence providing the Answer in Java.**
Code:
import java.io.File;
import java.util.Scanner;
//GetFiles Class
public class GetFiles {
public static void main(String[] args) {
//scanner instance to take input
from user in console
Scanner sc=new
Scanner(System.in);
System.out.println("Enter path :
");
//taking input
String path=sc.next();
//calling getFileInPath() method to
get the number of files in the path and print it.
System.out.println("No. of files in
path -- "+path+" is : "+getFilesInPath(path));
//closing scanner instance
sc.close();
}
//private static method to get number of files in a
given path
private static int getFilesInPath(String path) {
//new File(path) returns a
directory,
//.list returns a Array of Strings
for each file in the path,
//.length return the length of the
array
return new
File(path).list().length;
}
}
Output:
Enter path :
C:\sd
No. of files in path -- C:\sd is : 4