เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ค้นหาไฟล์ในเครื่อง

ต้องการเขียนโปรแกรมขนาดเล็กที่จะแสดงผลเฉพาะ ไฟล์ในเครื่อง จากไดเรกทอรีที่กำหนด โดยดึงรายการองค์ประกอบในไดเรกทอรีมาเก็บไว้ใน 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");
  }
}
แก้ไขและรันโค้ด