Why am I getting index out of bounds exception?

邮差的信 提交于 2019-11-29 16:55:57

In your code you get the value by index which is evaluated incorrectly.

  for (int i = binary.size(); i > -1; i = i - 1){
     System.out.print(binary.get(i));
  }

Assignment of binary.size() indeed out of bounds, because indexes counted from binary.size() to zero, but it is out of range which is bound from zero to binary.size()-1.

for (int i = binary.size(); i > -1; i = i - 1){

Assuming binary contains 8 elements, i first start with 8. However list/array etc in Java is 0-based, so the index should be 0-7. Of course it is going to give you error when you try to access binary.get(8)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!