BaşlayınÜcretsiz Başlayın

Yerel dosyaları bulma

Belirli bir dizindeki yalnızca yerel dosyaları yazdıracak küçük bir program yazmak istiyorsun. Dizin içindeki öğelerin listesini DIRECTORY_CONTENT içinde aldın, ancak:

  • Tüm öğeler önce türü, sonra öğenin kendisini içeriyor
  • /d dizin demek,
  • /f dosya demek
  • Bazı dosyalar gizli ve "." içeriyor
  • Diğer dizinlerdeki dosyalar yazdırılmamalı Hadi bunları şimdi düzeltelim!

Bu egzersiz

Orta Düzey Java

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Ögenin dosya mı dizin mi olduğunu kontrol etmek için .substring(a,b) ve .contains("") kullan.
  • Bir dosyanın gizli olup olmadığını, "." contains ettiğinde kontrol et.
  • Bir dosyanın yerel olduğundan, "/" içermediğinden emin olarak emin ol.
  • Her iki koşulu aynı anda kullanmak için doğru mantıksal operatörü kullan.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

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");
  }
}
Kodu Düzenle ve Çalıştır