始める無料で始める

ローカルファイルを見つける

指定したディレクトリ内で、ローカルファイル のみをだけ表示する小さなプログラムを書きたいとします。ディレクトリ内の要素一覧は DIRECTORY_CONTENT に取得できましたが、次の点に注意が必要です:

  • すべての要素は最初にタイプ、その後に要素名が続きます。
  • /d はディレクトリ、
  • /f はファイルを意味します。
  • 一部のファイルは非表示(hidden)で、"." を含みます。
  • 他のディレクトリにあるファイルは表示してはいけません。 では、これらを修正していきましょう!

この演習はコースの一部です

中級 Java

コースを見る

演習の手順

  • .substring(a,b).contains("") を使って、要素がファイルかディレクトリかを判定します。
  • "."contains しているとき、そのファイルは 非表示(hidden) です。
  • "/" を含まないことを確認して、ファイルが ローカル であることをチェックします。
  • 2つの条件を同時に使うために、正しい論理演算子を使用してください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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");
  }
}
コードを編集して実行