1

Given the following Java codes:

int test = createIntData(Column[8]);

private int createIntData (String realData) {
    if (realData == null) {
        return (int) (Math.random()*100); 
    }
    else {
        return Integer.parseInt(realData);
    }
}

This throws exception like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

This is because the argument only have an maximum index of 4. Then how to change the program to realize the function that: once the argument is out of index, return the value:

Math.random() * 100
6
  • 2
    The problem is in Column[8]. It's got nothing to do with your createIntData method, really. The argument is evaluated before the method gets called - so if evaluating the argument fails (as it is doing here), there's nothing the method can do about it. Commented Oct 15, 2014 at 13:47
  • 1
    @JonSkeet Column[8] and ArrayIndexOutOfBoundsException: 10 doesn't fit Commented Oct 15, 2014 at 13:50
  • Then how to verify the Column[8] first and do sth with it if it is out of index?@JonSkeet Commented Oct 15, 2014 at 13:50
  • Forget about the number '10', because I do not make a full copy of my codes. @TAsk Commented Oct 15, 2014 at 13:52
  • 1
    In Java, naming conventions dictate that variables begin with a lower case letter. This makes it easier to quickly tell the difference between types and variables. You can see by SME_Dev's answer that not following this convention can really throw people off. Commented Oct 15, 2014 at 13:57

3 Answers 3

1

I would go with allowing for check inside the method, by passing array and index:

public int createIntData(String[] values, int index) {
    if (values != null && index >= 0 && index < values.length) {
        return Integer.parseInt(values[index]);
    }
    return (int) (Math.random()*100);
}

Call it:

int test = createIntData(Column, 8);

This way the method can safely be called with any input (I left the potential exception in the parseInt, though)

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

1 Comment

realData should be values[index].
1

If 8 is outside the range of Column's length, that error is what you get. Change this

int test = createIntData(Column[8]);

to (using the ternary)

int test = createIntData((8 < Column.length) ? Column[8] : null);

Comments

1

There are 2 severe problems:

1.You should check, whether a given array index does exist:

Column[] array = new Column[someCapacity];
//fill the array

int i = 8;

if( i < array.length && i > -1 ){
    int test = createIntData(array[i]);
}

2.The array's type(Column) does not match the createIntData() input parameter (String)

Comments

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.