java索引越界异常,为什么我得到索引越界异常?

I've made this code to convert whole base 10 numbers into binary. The code I believe is everything that it needs to be but I can't get me ArrayLists to work. I've spent a few hours on this site and other trying countless changes to no avail. I've gotten the code to compile without and errors but as soon as I enter an int the program crashes.

Here is the code:

import java.util.Scanner;

import java.util.ArrayList;

public class BinaryConverter {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

ArrayList binary = new ArrayList();

int a = in.nextInt();

binary = binaryConverter(a);

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

System.out.print(binary.get(i));

}

}

public static ArrayList binaryConverter(Integer n) {

ArrayList remainder = new ArrayList();

while (n/2 != 0) {

remainder.add(n%2);

n = n/2;

}

remainder.add(n%2);

return remainder;

}

}

These are the exceptions java throws at me when I input a number.

Jons-iMac:java jon$ java BinaryConverter

142

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 8 out-of-bounds for length 8

at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)

at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)

at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)

at java.base/java.util.Objects.checkIndex(Objects.java:372)

at java.base/java.util.ArrayList.get(ArrayList.java:440)

at BinaryConverter.main(BinaryConverter.java:16)

I hope this is enough information.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值