Reputation: 880
So let's say I have an array called arr
with the values &&&&.&&
. I want to find the number of ampersands (&) that are after the decimal point and store the value into 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;
}
}
I'm not sure if this is the right approach. So the outside for
loop runs through each index value of the array. The inner for
loop starts at the decimal, and ends at the end of the array. Every time a new value is found, numDecimalDigits
is added by one. However, in my code I think numDecimalDigits
is returning an incorrect value.
Upvotes: 0
Views: 64
Reputation: 5092
No need to use array. It would be easy like this:(Assuming str
value must contains one '.
' )
int numDecimalDigits = str.split("\\.")[1].length();
Or you can do by subtracting str.length()-1
with indexOf(".")
int numDecimalDigits = str.length()-1 - str.indexOf(".");
Upvotes: 1
Reputation: 3605
You only need one loop:
boolean foundDot = false;
for (int i = 0; i < arr.length; i++) {
if(arr[i] == '.') {
foundDot = true;
} else if(foundDot) {
numDecimalDigits ++;
}
}
Upvotes: 1