-3

My problem is this the previous code words.lenght() is counting all the characters including space. What i want to do is count all characters excluding space which is ascii 32.

public static void main (String args[]){


        String words = "kickflip in the face yo!";
        int ff = 0;

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

            if(words.charAt(i) == (char) 32)
                continue;


            ff++;

        }

        System.out.print(ff);
tinker101
  • 33
  • 11
  • [`Character.isSpace`](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isSpaceChar(char))? How about `words.replace(" ", "").length()`? – MadProgrammer Feb 26 '15 at 01:50
  • That looks fine. What's your problem? – k_g Feb 26 '15 at 01:50
  • it says Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 17 at java.lang.String.charAt(Unknown Source) at TestKlass.main(TestKlass.java:15) – tinker101 Feb 26 '15 at 01:52
  • See http://stackoverflow.com/a/7694012/2055998 – PM 77-1 Feb 26 '15 at 01:53
  • @tinker101, it won't be at 17 with that string, it'll be at 24. In any case, both answers (to date), mine included, point out what the issue is. – paxdiablo Feb 26 '15 at 01:53

1 Answers1

0

Other than using <= in the for line where you should use < (resulting in an exception when you try to grab the character at index 24), and the missing closing brace (which I assume is just a typo), that code should work fine.

With those problems fixed, it gives you the correct value of 20:

public class Test {
    public static void main (String args[]){
        String words = "kickflip in the face yo!";
        int ff = 0;
        for (int i = 0; i < words.length(); i++)
            if (words.charAt(i) != ' ')
                ff++;
        System.out.print(ff);
    }
}

You'll notice I've made two other small mods which make the code better (in my opinion).

The first is to use ' ' rather than (char)32, the second is to slightly restructure the counting bit so you don't need continue.

There are no doubt other improvements that could be made but they'd tend to get away from the beginner level.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953