1

In Java. Let's say you're given the following Array. Or something similar

int[] anArray = {10, 20, 30, 40, 1000};

Is there a way to take the length of the array element at anArray[4]; ?

I need to know if the array[x] is == 4. As in 2004, or 1000, or 1968.

How can i do this?

1
  • 1
    What do you mean by length of an array element? Commented Feb 27, 2011 at 0:17

5 Answers 5

5

You can convert the element to a string and get the length of the string, or if its integers you can test if it's between 1000 and 9999.

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

Comments

3

Convert your array object to string and check is length :

anArray[x].toString().length

1 Comment

I doubt that the compiler is going to like this. You can't dereference an int and this isn't a case where autoboxing is going to be used.
1

You could convert the element to a string and then find the length of the string.

You could also use repeated division by 10 in a while loop to find your answer.

Comments

1
if (Integer.toString(anArray[x]).length() == 4) {
    // it's 4 long
}

Comments

0

Slightly geekier approach:

int lengthOfElement4 = (int) Math.floor((Math.log(anArray[4]) / Math.log(10) + 1);

@Mark's second option will probably be quicker though...

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.