Java:Int Array,测量数组元素的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5130621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:36:05  来源:igfitidea点击:

Java: Int Array, measure the length of the array element

javaarrays

提问by Snow_Mac

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 elementat anArray[4]; ?

有没有办法在 anArray[4]; 处获取数组元素的长度??

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

我需要知道数组 [x] 是否为 == 4。就像在 2004 年、1000 年或 1968 年一样。

How can i do this?

我怎样才能做到这一点?

回答by Mark Byers

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.

您可以将元素转换为字符串并获取字符串的长度,或者如果它是整数,您可以测试它是否在 1000 和 9999 之间。

回答by krtek

Convert your array object to string and check is length :

将数组对象转换为字符串并检查长度:

anArray[x].toString().length

回答by WuHoUnited

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.

您还可以在 while 循环中使用重复除以 10 来找到答案。

回答by Ted Hopp

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

回答by Mac

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...

@Mark 的第二个选项可能会更快...