【问题标题】:How to check if the all the indexes of an ArrayList has no file in them?如何检查 ArrayList 的所有索引中是否没有文件?
【发布时间】:2021-10-24 00:49:13
【问题描述】:

我搜索并找不到类似的问题。 我想检查ArrayList 的所有索引中是否没有文件(文件在其路径中不存在),显然这必须通过for-loopboolean 完成,所以我想要@987654324 @变成这样:

如果所有索引中都没有文件,boolean 为真。

如果一个或多个或所有索引在其路径中有文件boolean 为假。

使用下面的方法我有一个问题,如果其中一个索引(或者我应该说第一次出现)没有文件,则条件为 true ,但这不是我想要的,我希望它只有在所有索引都没有文件。

for (int i = 0; i < logopaths.size(); i++) {
            String s = logopaths.get(i);
            File file = new File(s);
            boolean exists = file.exists();
            if (exists){
                // do somethng
            } else {
                // do some other thing
            }
        }

【问题讨论】:

  • 只计算你的“if”为假的次数并与 logopaths.size();

标签: java android loops boolean


【解决方案1】:

这里(:

// Array of logo paths
ArrayList<String> logoPaths = new ArrayList<>();

// File variable declaration
File file = null;
// The flag which indicates all the file paths are exists
boolean flag = ture;

for (int i = 0; i < logoPaths.size(); i++) {
    // Creating a file instance in order to get access to file operations
    file = new File(logoPaths.get(i));
    
    // If one file exists the flag will be false and we will break the for loop. 
    // If all the files are not exists the flag will stay true.
    if (file.exists()) {
        flag = false;
        break;
    }
}

【讨论】:

    【解决方案2】:

    或者让它成为一个方法:

        public boolean fileFound(List<String> logopaths) {
            boolean atLeastOneFileExists = false;
            for (int i = 0; i < logopaths.size() && !atLeastOneFileExists; i++) {
                String s = logopaths.get(i);
                File file = new File(s);
                atLeastOneFileExists = file.exists();
            }
            return atLeastOneFileExists;
        }
    
    

    【讨论】:

    • 感谢上帝保佑你
    猜你喜欢
    • 2017-07-03
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多