Začněte nyníZačněte zdarma

Hledání lokálních souborů

Chceš napsat malý program, který vypíše pouze lokální soubory v daném adresáři. Podařilo se ti načíst seznam prvků adresáře uložený v DIRECTORY_CONTENT, ale:

  • Každý prvek obsahuje nejprve typ, a pak samotný prvek
  • /d označuje adresář,
  • /f označuje soubor
  • Některé soubory jsou skryté a obsahují "."
  • Soubory z jiných adresářů se nemají vypisovat Pojďme to teď napravit!

Toto cvičení je součástí kurzu

Intermediate Java

Zobrazit kurz

Pokyny k cvičení

  • Pomocí .substring(a,b) a .contains("") zjisti, jestli je prvek soubor, nebo adresář.
  • Ověř, zda je soubor skrytý — takový soubor contains řetězec "." .
  • Zkontroluj, že je soubor lokální — nesmí obsahovat "/".
  • Použij správný logický operátor, aby platily obě podmínky zároveň.

Interaktivní cvičení na vyzkoušení si v praxi

Vyzkoušejte si toto cvičení dokončením tohoto ukázkového kódu.

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");
  }
}
Upravit a spustit kód