简体   繁体   English

为什么 Java 永远不会到达这个 if/else 的结尾?

[英]Why does Java never reach the end of this if/else?

I've been scratching my head at this for hours now, but I can't seem to figure this one out.我已经为此挠头好几个小时了,但我似乎无法弄清楚这一点。 I'm writing a program that has a constant loop going in a Thread, which occasionally sends back data to another part of the program using an Arraylist.我正在编写一个程序,该程序在线程中具有恒定循环,该程序偶尔使用 Arraylist 将数据发送回程序的另一部分。

I only want to send this data back after I have gathered 11 items in my arraylist.我只想在我的 arraylist 中收集 11 个项目后将这些数据发回。 So I used this code:所以我使用了这段代码:

//The rest of the loop in which i gather the values for key and velocity.

    notenbuffer.add(new Noot(key,velocity));
    if (notenbuffer.size() > 10){
    System.out.println("Notenbuffer > 10, verstuur data");
        
    if (notenbuffer.isEmpty()){
          System.out.println("buffer is empty!");

    }
    else {
          usbRead.writeNotes(notenbuffer);
          System.out.println("emptied the buffer!");
          notenbuffer.clear();
    }
        
    }

Now for some weird reason the program never empties the Arraylist, and just keeps on adding items to it.现在由于一些奇怪的原因,程序永远不会清空 Arraylist,而是继续向其中添加项目。 I've checked and it does in fact reach the usbRead.writeNotes(notenbuffer) part because this function gets called correctly.我已经检查过了,它实际上确实到达了usbRead.writeNotes(notenbuffer)部分,因为这个 function 被正确调用。 When I use the debugger it simply skips to the beginning of the loop after this function was called.当我使用调试器时,它只是在调用此 function 后跳到循环的开头。

Is there a way in which I can empty an Arraylist once it reaches a certain size?有没有一种方法可以在 Arraylist 达到一定大小后清空它?

Edit: I made a logic error by writing if (notenbuffer.isEmpty()) this will always be false because I am already in an if statement which requires this to be false.编辑:我写了一个逻辑错误if (notenbuffer.isEmpty())这将永远是假的,因为我已经在一个 if 语句中,它要求它是假的。

Did you put your second if inside your first by accident?如果你不小心把你的第二个放在你的第一个里面吗? (The missing indentation seems to suggest so). (缺少的缩进似乎暗示了这一点)。 Having if (notenbuffer.isEmpty()) inside the if (notenbuffer.size() > 10) block makes no sense at all logically.在 if (notenbuffer.size() > 10) 块中包含 if (notenbuffer.isEmpty()) 在逻辑上根本没有意义。 After all if your List size is > 10 then the list is obviously not empty.毕竟,如果您的列表大小> 10,那么列表显然不是空的。 So if (notenbuffer.isEmpty()) can never be true at all.所以 if (notenbuffer.isEmpty()) 永远不可能是真的。 – OH GOD SPIDERS 15 mins ago – 天哪,蜘蛛 15 分钟前

This was indeed the problem.这确实是问题所在。 Removing this exposed an NoClassDefFoundError that needed resolving.删除它会暴露一个需要解决的 NoClassDefFoundError。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM