简体   繁体   English

java.lang.ArrayIndexOutOfBoundsException:2> = 2

[英]java.lang.ArrayIndexOutOfBoundsException: 2 >= 2

I'm brand new to Java and my first assignment was to implement a "for" loop. 我是Java的新手,我的第一个任务是实现“ for”循环。 I wrote this program in C++ and it compiles in Java, but I got an error at runtime. 我用C ++编写了该程序,并用Java进行了编译,但是在运行时出现错误。 Can anyone tell me what's wrong? 谁能告诉我怎么了?

import java.util.Scanner;
import java.util.Vector;

public class GlobalMembersMain
{

    public static Vector<Integer> get_prime_factors(int number)
    {

        Vector<Integer> primefactors = new Vector<Integer>();
        for (int j = 2; j <= number; j++)
        {
            if (number % j == 0)
            {
                primefactors.add(j);
                number = number / j;
                j = 1;
            }
        }
        return primefactors;
    }

    public static void main(String[] args)
    {
        int number;
        int count = 1;
        System.out.print("Enter integer to analyse:");
        System.out.print("\n");
        Scanner scan = new Scanner(System.in);
        number = scan.nextInt();
        Vector<Integer> primefactors = new Vector<Integer>();
        primefactors = get_prime_factors(number);
        System.out.print("Prime factors are ");
        for (int a = 0; a < primefactors.size() + 1; a++)
        {
            if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
            {
                count++;
            }
            else
            {
                System.out.print(primefactors.elementAt(a));
                System.out.print(" (");
                System.out.print(count);
                System.out.print(") ");
                count = 1;
            }
        }
        System.out.print("\n");
    }
}

The output: 输出:

Enter integer to analyse:
10
Prime factors are 2 (1) Exception in thread "main" java.lang.ArrayIndexOutOfBoun
dsException: 2 >= 2
        at java.util.Vector.elementAt(Unknown Source)
        at GlobalMembersMain.main(GlobalMembersMain.java:36)
    for (int a = 0; a < primefactors.size() + 1; a++)
    {
        if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
        {
            count++;
        }

Is exceeding the size of the primefactors collection. 超出primefactors集合的大小。 By 2, in fact. 减2,实际上。

Change to primefactors.size() - 1 to avoid this error. 更改为primefactors.size() - 1以避免此错误。

Arrays are zero based, which I imagine you are aware of. 数组是从零开始的,我想您已经知道了。 What you may not be aware of is that in Java a List is backed by an array as well. 您可能不知道的是,在Java中, List也由数组支持。 When you invoke primefactors.size() +1 you are getting one more than you would possibly want. 当您调用primefactors.size() +1您得到的可能比您想要的多。 For instance is pf is of size 1 your loop will do the following: 例如pf的大小为1,您的循环将执行以下操作:

pf.get(0);  //returns the only value in the list  
pf.get(1); // element doesn't exist

Now the other thing is you do not want to use Vector , generally speaking in Java. 现在,另一件事是您不想使用Vector ,通常来说,它是用Java编写的。 It is a synchronized collection. 这是一个同步的集合。 What you want is List/ArrayList. 您想要的是List / ArrayList。

OTHER CODE ISSUES 其他代码问题

public static Vector<Integer> get_prime_factors(int number)

this does not need to be static. 这不必是静态的。 Also naming convention is camel case in Java so your function name should be getPrimeFactors(int number) 另外,Java中的驼峰式命名约定也是如此,因此您的函数名称应为getPrimeFactors(int number)

GlobalMembersMain

Should most likely be named GlobalMember as classes are to be singular in nature and I believe you added Main to indicate it was the class that holds the main function. 应该最有可能将GlobalMember命名为类,因为类本质上是单数,我相信您添加了Main来表示它是持有main函数的类。

In your main function you would do this: 在主要功能中,您需要这样做:

GlobalMember member = new GlobalMember(); GlobalMember成员=新的GlobalMember();
member.getPrimeFactors(number); member.getPrimeFactors(number);

This is where the problem is: 这是问题所在:

for (int a = 0; a < primefactors.size() + 1; a++)
    {
        if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
        {
            count++;
       }

//...

primefactors.elementAt(a+1) for the last element in your collection will throw the exception (AIOB). primefactors.elementAt(a+1)最后一个元素的primefactors.elementAt(a+1)将引发异常(AIOB)。

Remember that arrays, lists and vectors in Java are zero-based. 请记住,Java中的数组,列表和向量都是从零开始的。 In your case, the primefactors vector will consist of two elements, available at index 0 and 1 respectively. 在您的情况下, primefactors向量将包含两个元素,分别在索引0和1处可用。

The problem you are facing is that you try to access the element primefactors.elementAt(2) which does not exist. 您面临的问题是您尝试访问不存在的元素primefactors.elementAt(2)

One problem is the break condition in the loop: 一个问题是循环中的中断条件:

for (int a = 0; a < primefactors.size() + 1; a++) { 
    // ... 
}

The first time, a will be 0, the second time 1 which are both fine. 第一次, a将为0,第二次为1 ,两者都很好。 However, the loop will not break the third time, because a will equal 2, which is less than primefactors.size() + 1 . 但是,该循环不会第三次中断,因为a等于2,小于primefactors.size() + 1 Consequently, there will be a call to primefactors.elementAt(2) which does not exist and the program will blow up. 因此,将存在对primefactors.elementAt(2)的调用,该调用不存在,并且程序将primefactors.elementAt(2)

There is also a second problem inside the loop since you increment the loop variable by one during the comparison: 循环中还有第二个问题,因为在比较期间将循环变量增加了一个:

if (primefactors.elementAt(a) == primefactors.elementAt(a+1)) { 
    // ... 
}

Yet again, your program will fail if you pass 2 as an argument to primefactors.elementAt(...) 再一次,如果将2作为参数传递给primefactors.elementAt(...) ,则程序将失败primefactors.elementAt(...)

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

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