3

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;
}
6
  • 1
    When asking about an error, please post the error message. There could be a few things going on, and the actual error is more helpful than just the line number. Commented Aug 1, 2013 at 2:14
  • 1
    @hexafraction Java doesn't do shell-style name arguments. args[0] is the first argument, not the name of the class. Commented Aug 1, 2013 at 2:15
  • Java does not behave this way (First argument is program name). Does the assert evalutate to true? Commented Aug 1, 2013 at 2:20
  • 1
    Regarding the 'compiler-errors' tag on this, ArrayIndexOutOfBoundsException is not a compilation error; it's a runtime error. Commented Aug 1, 2013 at 2:22
  • If not then you must define arguments to your program. Otherwise the array "args" will be size 0 and 0 will be out of bounds. Commented Aug 1, 2013 at 2:22

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is good advice, but if the tag is correct, he's having compiler problems, not runtime.
@chrylis do you see any compiler problems in the line with trouble? it is more likely that: 1) he's doesn't have a parseable number as first argument, or 2) the doesn't even have any arguments in the command line
No, it looks perfectly correct, but it is tagged compiler-errors.
1

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}

3 Comments

Exactly one, because of the assert condition.
@chrylis asserts are not always on
@RiaD No, they're not, but that's what he's using for error-checking in this example. It's not the best choice, but that's another issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.