0

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.

4
  • 1
    What is this supposed to be doing -- (arr[pos] = '.')? What it does is set arr[pos] to '.' (whatever pos is). Commented Feb 10, 2014 at 2:33
  • Well what I tried doing was to start the for loop at where the decimal point began, and end the loop at the end of the array. pos is just short for "position" (i.e. position in array) Commented Feb 10, 2014 at 2:38
  • Using indexOf on a String would make more sense. Or a single loop from 0 to array.length, comparing to '.'. (And you compare for equal with ==. = is assignment.) Commented Feb 10, 2014 at 2:38
  • (arr[pos] = '.') doesn't tell you where the decimal point is, it assigns '.' to arr[pos]. Commented Feb 10, 2014 at 2:39

2 Answers 2

1

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 ++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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(".");

4 Comments

Wouldn't make a lot more sense to use indexOf and not bother creating new strings you don't need??
@HotLicks which new string you are referring to?
The two strings created by split. (Not to mention the String array.)
Ok, I have added your suggestion.

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.