Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ArrayIndexOutOfBoundsException

Tags:

java

I'm a novice Java programmer. I dont know what is wrong with the main method, it keeps pointing me to this line

    int x = Integer.parseInt(args[0]);

this is my code

public static void main(String[] args) {

    assert args.length == 1;
    int x = Integer.parseInt(args[0]);
    while (x != 1) {
        x = nextInt(x);
        System.out.print(" " + x);
    }
}

public static int nextInt(int x) {
    if (x % 2 == 0) {
        return x / 2;
    } else
        return 3 * x + 1;
}
like image 661
user2640331 Avatar asked May 12 '26 21:05

user2640331


2 Answers

I'm going to assume that you are using a number in the first argument of your program call.

You are using asserts, verify that assertions are activated. Execute your code with the VM argument: -ea.

like image 185
morgano Avatar answered May 14 '26 11:05

morgano


Simply said, in Java the java.lang.ArrayIndexOutOfBoundsException means there is no array element in the specified index of your array.

So make sure you input at least 1 argument when running your java app from the command prompt. In your case, it should be parsable to an Integer.

For Example:

java {class_name_with_main_methof} {argument_1} {argument_2}
like image 23
Dinusha Kariyawasam Avatar answered May 14 '26 11:05

Dinusha Kariyawasam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!