Java线程ArrayIndexOutOfBoundsException
我用线程编写了一个程序(用于自学),它使用两个线程计算数组元素的乘法。但对于这两个线程,我都得到了一个数组索引OutofBoundsException。错误如下所示:Java线程ArrayIndexOutOfBoundsException,java,arrays,multithreading,exception,indexoutofboundsexception,Java,Arrays,Multithreading,Exception,Indexoutofboundsexception,我用线程编写了一个程序(用于自学),它使用两个线程计算数组元素的乘法。但对于这两个线程,我都得到了一个数组索引OutofBoundsException。错误如下所示: Exception in thread "Thread-1" Exception in thread "Thread-0" Executing multiplying of last2elements java.lang.ArrayIndexOutOfBoundsException: 1 a
Exception in thread "Thread-1" Exception in thread "Thread-0" Executing multiplying of last2elements
java.lang.ArrayIndexOutOfBoundsException: 1
at FirstPart.run(FirstPart.java:12)
java.lang.ArrayIndexOutOfBoundsException: 1
at SecondPart.run(SecondPart.java:10)
Java代码:
java
public class FirstPart extends Thread {
int multiply = 1;
static int n;
static int[] v = new int[n];
public void run() {
System.out.println("Executing multiplying of first "+MultiplyDemo.cap1+"elements");
for(int i = 1; i <= MultiplyDemo.cap1; i++) {
multiply = multiply * FirstPart.v[i];
System.out.println("Multiplication is "+ multiply);
}
}
}
公共类第一部分扩展线程{
整数乘=1;
静态int n;
静态整数[]v=新整数[n];
公开募捐{
System.out.println(“执行第一个“+MultiplyDemo.cap1+”元素的乘法”);
for(int i=1;i使您的两个for循环都指向此:
for(int i=0; i < MultiplyDemo.cap1; i++)
for(int i=0;i
和PS:请以适当的格式发布问题,以便有人能够帮助解决。MultiplyDemo。cap1
比您的大n
导致您的for循环尝试访问不存在的索引:
for(int i=1;i<=MultiplyDemo.cap1;i++)
multiply=multiply*FirstPart.v[i]; // Misses index 0 and tries to go to index n, when n-1 is max
for(int i=1;i数组索引是基于0的;如果数组大小为n
则有效索引在范围0..n-1
所有for
循环都使用检查,您的“n”默认值为0,因此您的v数组的长度为0
这就是为什么索引超出了范围
在main方法中,您正在初始化一个新的“v”变量。请记住,此“v”数组与“FirstPart”中的静态“v”数组不同。FirstPart。v仍然是一个空数组。您正在从main()中将值赋给n方法,并将值初始化为一个本地数组,该数组不影响FirstPart.v但它不会执行预期的操作,第二个Part类应继续从MultyplyDemo.cap1相乘,直到结束(数组的后半部分)。否,v数组以Decellation方式初始化,而n为0。主要是一个不同的实例(也称为v)很抱歉,我的意思是n
是在mainshill中初始化的,不是真的。main初始化一个不同的实例,与FirstPart.v无关,它在main执行任何操作之前在declaration中初始化。根据mainFirstPart.n=s.nextInt()中的上述代码
n
是一个静态变量-它怎么可能是一个不同的实例?n在v已经初始化之后在main中初始化,因此在main中初始化n不会影响任何事情。但是我不知道如何修改代码,如果我将n,v,声明移动到main中,我无法访问它们,我会出错。我是一个初学者,所以我我不知道在这种情况下该怎么办。我知道我做错了什么,但你能告诉我该怎么做吗?这对我来说意味着整个世界!替换我只是一个问题:你是在自学线程,而你在数组上写索引循环时遇到了麻烦吗?我认为你应该重新思考你的学习程序stEPS
for(int i=0; i < MultiplyDemo.cap1; i++)
for(int i=1;i<=MultiplyDemo.cap1;i++)
multiply=multiply*FirstPart.v[i]; // Misses index 0 and tries to go to index n, when n-1 is max
Object[] array = new Object[size];
for(int i = 0;i < array.length;i++) {
..
}