我的代码遇到问题。我知道为什么会出现索引越界错误。这段代码假设将 2 个字节数组合并为一个。根据“list[position] = byteAdd[t];”但我不知道出了什么问题。这些数组初始化为 200 字节大小。
Scanner input = new Scanner(System.in);
System.out.println("Enter a web Address");
String net = input.nextLine();
String nets [] = net.split("\\.");
byte[] length = new byte [200];
byte[] byteAdd= new byte[200];
int bytelength = byteAdd.length*2;
byte[] list = new byte [200];
for (int i = 0 ; i<nets.length; i++ )
{
length[i]= (byte)(double) ( nets[i].length());
System.out.println(length[i]);
}
for (int i = 0 ; i<nets.length; i++ )
{
byteAdd = nets[i].getBytes();
}
int position= 0 , max= 0;
for (int i = 0 ; i<bytelength; i++)
{
list[position]=length[i];
position++;
for (int t = 0 ; t<length[i]; t++)
{
list[position] = byteAdd[t];
System.out.println(t+" "+length[i]);
System.out.println("Array lenght" + list.length);
//System.out.println(t+"inner" + position);
position++;
}
//System.out.println(i+"outter");
}
这是堆栈跟踪吗?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at test.test.main(test.java:51)
错误在这一行list[position] = byteAdd[t];
最佳答案
您的list = new byte [200];
声明大小为200
的列表
字节长度
的大小为200*2
= 400
所以当你说
for (int i = 0 ; i<bytelength; i++)
这意味着
for (int i = 0 ; i<400; i++) //whereas all array is limited to size 200 and that's throwing exception!
因此,在增量指针 position++
中,该值最大为 399,而数组大小限制为 200
所以 list[position]
上升到 list[201-400]//应在 200 处截断
关于java - 索引越界错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23210857/