0

I'm pretty new when it comes to coding in java (or coding in general), and I want the code below to print out only the end result (3), but it prints everything beforehand too, then once it reaches the end it gives me a runtime error

package programs;

public class practice2 
{
    public static void main(String [] args)
    {
        //create a program that counts spaces in a string
        String sentence = "test if this works";

        int count = 0;
        for(int i = 0; i <= sentence.length(); ++i)
        {
            String space = sentence.substring(i, i+1);
            if(space.equals(" "))
            {
                count = count + 1;
            }
            System.out.println(count);
        }
    }
}
  • 3
    _once it reaches the end it gives me a runtime error_ Let me guess. Is it `ArrayIndexOutOfBoundsException`? Learn to use a debugger. – Abra Jan 09 '21 at 06:26
  • When you see a runtime error like that, take care to read it carefully and understand *why* its happening, In this case, it should be clear you have an [off-by-one error](https://en.wikipedia.org/wiki/Off-by-one_error) in your loop -- which is very frequently the case. – costaparas Jan 09 '21 at 06:31
  • For the other issue, just move `System.out.println(count);` *outside* (i.e. *after* the loop) of the loop, rather than running it in every iteration as it currently does. – costaparas Jan 09 '21 at 06:32
  • The runtime error it gives me is StringIndexOutOfBoundsException Sorry, I should have included this in the question – Jiggyboneless Jan 09 '21 at 06:32

4 Answers4

1

To get the final output, you need to move the print statement outside of the for loop. As for the runtime error, change the looping condition to i < sentence.length() instead of i <= sentence.length() because indexing starts from 0 and end at length-1.

Jyotirmay
  • 513
  • 6
  • 22
0

Problem

Your for loop goes all the way to the length of the string

 i<=sentence.length()

When it should be

  i<sentence.length()

Suggestion

Blank space is just a character so you don't need substring but just to check for the character like this

char ch=sentence.charAt(i);
if(ch==' ')//do something

Your final code

    String sentence = "test if this works";

    int count = 0;
    for(int i = 0; i < sentence.length(); i++)
    {
        char ch=sentence.charAt(i);
        if(ch==' ')
        {
            count++;
        }
    }
    System.out.println(count);

Or if you want a one liner

       int count=sentence.trim().split(" ").length-1;

Because the number of spaces is the number of words(which I assume are seperated by spaces so we split the sentence at those parts)-1

Sync it
  • 1,180
  • 2
  • 11
  • 29
0

Say you have a string hello then the length is 5. String starts from 0th index hence you should consider iterating it only till less than length i.e <5 is 4[0 to 4] in this case. Hence you conditional check block would become i <= sentence.length() to i < sentence.length(). This is the actual cause of exception Also, i would encourage you to read this thread

To check space we have an inbuilt method in java which we can use https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isWhitespace(int)

        String sentence = "test if this works";
        int count = 0;
        for (int i = 0; i < sentence.length(); ++i) {
            final char character = sentence.charAt(i);
            if (Character.isWhitespace(character)) {
                System.out.println("Space encountered at index: " + i);
                count = count + 1;
                System.out.println(count);
            }
        }

        System.out.println("Total spaces in sentence : " + count);
silentsudo
  • 6,730
  • 6
  • 39
  • 81
0

You have two problems:

  • your for loop is iterating over the end of the string
  • the println must be outside the loop to run only once

In the for loop, the variable i must iterate between 0 (the first character in the String) and sentence.length()-1 (the last character), so you must change the condition to:

i < sentence.length()
Edgar Domingues
  • 930
  • 1
  • 8
  • 17