Java: Int Array, measure the length of the array element
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 anArra开发者_如何学Cy[4]; ?
I need to know if the array[x] is == 4. As in 2004, or 1000, or 1968.
How can i do this?
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.
Convert your array object to string and check is length :
anArray[x].toString().length
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.
if (Integer.toString(anArray[x]).length() == 4) {
// it's 4 long
}
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...
精彩评论