Search code examples
javaexceptionruntimebufferedreadercounting

Counting blank spaces, tabs and new lines in java without file handling


This is the code I've written for counting the number of spaces, tabs and newlines in a string entered by the user(new line is marked by a full stop (".") and I'm doing this without file handling. This code is throwing a string out of bounds exception during runtime and I'm not able to figure out why. Please help.

import java.io.*;
class Specialchars
{
    public static void main(String arg[]) throws IOException
    { 
        BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter one or more lines");
        String s=obj.readLine();

        int count1=0,count2=0,count3=0;

        for(int i=0; i<=s.length(); i++)
        {
            char ch=s.charAt(i);
            if(ch==' ')
            {
                count1++;
            }
            else    
            if(ch=='\t')
            {
                count2++;
            } 
            else    
            if(ch=='.')
            {
                count3++;
            }
        }
        System.out.println("The number of blank spaces is = "+count1);
        System.out.println("The number of tabs is = "+count2);
        System.out.println("The number of new lines is = "+count3);
    }
}

Solution

  • you should use

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

    instead of

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

    strings like arrays are enumarated starting from 0 so the last index is length() - 1