Break语句总是被执行

马蒂亚斯·雷斯

这可能是一个愚蠢的问题,但是我们是初学者,但是我没有找到解决问题的答案,所以这里是:我们正在开发文件系统(基于小型),并且我们有这种方法应该从以下位置移动文件一个目录到另一个。(从一个文件或目录中删除文件或目录,然后将其添加到另一个文件中。)

我们正在使用ArrayLists来存储Items(Item则是Directory和File的超类)。

由于必须按照字母顺序对所有内容进行排序,因此移动方法包含一个while循环,以验证必须将项目放置在何处(目录或文件没有任何首选项),但由于某种原因,我插入的break语句始终会执行(或至少这就是我认为的原因。)谢谢!

这是代码:

    if(item != null){
        boolean bool = false;
        int i = 0;
        loop: while(!bool && i <= items.size()-1) {
            if(i==0) {
                if(checkIfAlphabetic(item.getName(), items.get(0).getName())){ items.add(0,item);
                bool = true;
                }
                else{
                    break loop;
                }
            }
            else if(checkIfAlphabetic(items.get(i-1).getName(), item.getName()) && checkIfAlphabetic(item.getName(), items.get(i).getName() )) {
                items.add(i, item);
                bool = true;
            }
            else i++;
        }
        if(!bool){
            items.add(item);
        }
        setModificationTime();
    }

如果有些事情不清楚,我已经为自己辩解。

PS。同样由于某种原因,我要添加的项目总是被添加两次。

根据要求,checkIfAlphabetic的代码:

        private boolean checkIfAlphabetic(String search, String target){
    int[] searchInt = search.codePoints().toArray();
    int[] targetInt = target.codePoints().toArray();
    int i = 0;
    while(i<search.length() && i<target.length()){
        if(searchInt[i] > targetInt[i]){
            return false;
        }
        else if(searchInt[i] < targetInt[i]) return true;
        else i++;
    }

    if(search.length() < target.length()){
        return true;
    }
    else return false;

}
奥利维尔·格雷戈尔(OlivierGrégoire)

您的while循环有问题。无论如何,它将始终在第一次迭代后停止。

这就是按语句顺序发生的情况。这是伪代码,不是Java。请勿复制/粘贴,否则将无法正常工作。

boolean bool = false;
int i = 0;
// entering the while loop:
if (!bool && i <= items.size() - 1) // returns true. We go in the while loop.
if (i == 0) // returns true, we go in that block.
if (check... ) // if this returns true, this happens:
    bool = true;
else // if the previous statement returns false, this happens:
    break;

因此,在这里,如果check ...返回false,我们将退出循环。在另一种情况下,让我们继续:

// nothing else happens inside the loop, so go back to the loop condition.
if (!bool && i <= items.size() - 1) // Hey, wait a minute, bool is true. So "not" true is false. The condition is therefore not met, let's leave the loop.

因此,无论执行什么操作,代码都将退出循环,这就是发生的情况。在您的情况下,bool = true几乎等于break

这是您需要解决的问题。

如果我必须编写您的代码,这就是我的方法:

List<Item> items = ... ;
java.util.Collections.sort(items, new ItemNameComparator());

 private static class ItemNameComparator implements Comparator<Item> {
  @Override
  public int compare(Item a, Item b) {
    return a.getName().compareTo(b.getName());
  }
}

如果您使用Java 8:

List<Item> items = ...;
items.sort((a, b) -> a.getName().compareTo(b.getName()));

所有工具都存在于Java库中,请使用它们,而不是一次又一次地重新实现它们。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章