从数组中获取值

时间:2014-02-10 02:27:50

标签: java arrays

因此,假设我有一个名为arr的数组,其值为&&&&.&&。我想找到小数点后面的&符号(&)并将值存储到numDecimalDigits

int numDecimalDigits = 0;

char[] arr = new char[7]

for (int i = 0; i < str.length(); i ++)
{
    for (int decimal = (arr[pos] = '.'); decimal <= arr.length; decimal ++)
    {
        numDecimalDigits += 1;
    }
}

我不确定这是否是正确的做法。因此,外部for循环遍历数组的每个索引值。内部for循环从小数开始,到数组末尾结束。每次找到新值时,numDecimalDigits都会加1。但是,在我的代码中,我认为numDecimalDigits返回的值不正确。

2 个答案:

答案 0 :(得分:1)

无需使用数组。这很简单:(假设str值必须包含一个'.')

    int numDecimalDigits = str.split("\\.")[1].length();

或者您可以使用str.length()-1

减去indexOf(".")
    int numDecimalDigits = str.length()-1 - str.indexOf(".");

答案 1 :(得分:1)

你只需要一个循环:

boolean foundDot = false;
for (int i = 0; i < arr.length; i++) {
    if(arr[i] == '.') {
        foundDot = true;
    } else if(foundDot) {
        numDecimalDigits ++;
    }
}