로컬 파일 찾기
주어진 디렉터리에서 로컬 파일만 오로지 출력하는 작은 프로그램을 작성하려고 해요. 디렉터리의 요소 목록은 DIRECTORY_CONTENT에 가져왔는데, 다음과 같은 규칙이 있어요:
- 모든 요소는 먼저 타입이 오고, 그다음에 요소가 와요.
/d는 디렉터리,/f는 파일을 의미해요.- 일부 파일은 숨김 상태이며
"."를 포함해요. - 다른 디렉터리에 있는 파일은 출력하면 안 돼요. 이제 이 부분을 바로잡아 볼게요!
이 연습은 강의의 일부입니다
중급 Java
연습 안내
- 요소가 파일인지 디렉터리인지 확인하려면
.substring(a,b)와.contains("")를 사용하세요. - 파일이
"."를contains할 때 숨김인지 확인하세요. "/"를 포함하지 않도록 확인해 파일이 로컬인지 검사하세요.- 두 조건을 동시에 적용하려면 올바른 논리 연산자를 사용하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
class ls {
static boolean isFile(String elem) {
// Check that the first 3 characters of the element contain /f as a substring
return elem.____(0, 3).____("/f");
}
static boolean isHidden(String elem) {
// Use the appropriate method to make sure that file is hidden
return elem.____(".");
}
static boolean isNonLocal(String elem) {
// Use the correct method to determine whether a file is in a directory
return elem.____(____, elem.length()).____(____);
}
public static void main(String[] args) {
int hiddenCounter = 0, directoryCounter = 0, nestedCounter = 0;
for (String elem : DIRECTORY_CONTENT) {
if (isFile(elem)) {
if (!isHidden(elem)) System.out.print(elem.substring(2));
// Use a logical operator to make it correct
else if (isHidden(elem) ____ !isNonLocal(elem)) hiddenCounter++;
else nestedCounter++;
} else directoryCounter++;
}
printer(hiddenCounter, directoryCounter, nestedCounter);
}
static String[] DIRECTORY_CONTENT = {"/d .Trash", "/f .history", "/d Applications", "/f tmp", "/f script", "/d Documents", "/f Documents/.bankAccounts", "/f .sshKeys", "/d Pictures", "/f content", "/f Documents/file"};
static void printer(int hiddenCounter, int directoryCounter, int nestedCounter) {
System.out.println();
System.out.println("With :\n" + hiddenCounter + " hidden files,\n" + directoryCounter + " directories,\nAnd " + nestedCounter + " nested files");
}
}