1

I can't get this program to count the spaces, I have a feeling there is a logic error in the loop, but I am too inexperienced to figure it out myself. Any tips?

System.out.print("Enter a string: ");
String myString = keyboard.next();
int numBlanks = 0;

//find string length
int length = myString.length() - 1;
System.out.println("length " + length);

for(int sequence = 0; sequence >= length; ++sequence);
{

    if(myString.charAt(length)==' ')
    {
        numBlanks += 1;
        length -= length;
    }
    else 
        length -= length;

}
1
  • 2
    ( With standard coding conventions, you wouldn't get the problem of the spurious semicolon on the for loop. ) Commented Sep 26, 2010 at 15:49

4 Answers 4

9

There are few bugs I can see:

Semicolon at the end of for loop. Remove it.

Next

sequence >= length

should be

sequence <= length

and

if(myString.charAt(length)==' ')

should be

if(myString.charAt(sequence)==' ')

and you need to change length at all as you are already changing sequence.

So we get:

for(int sequence = 0; sequence <= length; ++sequence) {

    if(myString.charAt(sequence)==' ') {
        numBlanks += 1;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 but think there should be a "don't" in: and you need to change length at all
3

sequence >= length is spoken aloud as "sequence is greater than or equal to length." It is initialized to zero. When will it be greater than or equal to length?

Comments

1

In addition to the errors others have pointed out, there are violations of convention here; you're calculating the length as n - 1, and then comparing <= (well, >=, but should be <=). Typically, unless there is very good reason, our for loops look like this:

for (int i = 0; i < n; i++) {
    ...
}

In your case, this would be expressed as:

for (int i = 0; i < myString.length(); i++) {
    ...
}

It is also conventional to stick with "i" as the loop variable, unless there's good reason to use another; in your case, "sequence" is just confusing.

Comments

0

First issue:

change

for(int sequence = 0; sequence >= length; ++sequence);

to

for(int sequence = 0; sequence <= length; ++sequence);  //flipped >= to <=

Second issue:

change

I am too inexperienced to figure it out myself.

to

This will be some good practice for debugging.  //int confidence should never be negative

:D

1 Comment

While you're fixing the 'first issue', remember to also remove the extra semicolon at the end of the for sentence :-)

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.