尋找本機檔案
你想寫一個小程式,只列印給定目錄中只有那些本機檔案。你已經能取得目錄中的元素清單,存放在 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");
}
}