Counting special characters as spaces in java

I'm working on MacOS, with JDK 8. I want to count the number of special characters in the given string, but in the given code, special characters are counted as spaces. What should I do?

public static void main(String args[])
{
 String str;
 int lc=0,uc=0,d=0,s=0,spc=0;
 Scanner sc=new Scanner(System.in);
 System.out.print("Enter the string:");
 str=sc.nextLine();

 for(int i=0;i<str.length();i++)
   {
    if(str.charAt(i)>='a' && str.charAt(i)<='z')
    {
    lc++;
    }
    else if(str.charAt(i)>='A' && str.charAt(i)<='Z')
    {
    uc++;
    }
    else if(str.charAt(i)>='0' && str.charAt(i)<='9')
    {
    d++;
    }
    else if(str.charAt(i)>=32)
    {
    s++;
    }
    else if(str.charAt(i)>=33 && str.charAt(i)<=47 || str.charAt(i)==64)
    {
    spc++;
    }
   }
System.out.println("number of small characters in "+str+" are:"+lc);
System.out.println("number of CAPITAL characters in "+str+" are:"+uc);
System.out.println("number of digits in "+str+" are:"+d);
System.out.println("number of Spaces in "+str+" are:"+s);
System.out.println("number of Special characters in "+str+" are:"+spc);
}

This is the output I'm getting:

Enter the string:abc23@#$% 

number of small characters in abc23@#$% are:3

number of CAPITAL characters in abc23@#$% are:0

number of digits in abc23@#$% are:2

number of Spaces in abc23@#$% are:4

number of Special characters in abc23@#$% are:0

It should be displaying 4 special characters instead of 4 spaces.

1 answer

  • answered 2019-08-18 15:26 Butiri Dan

    Change str.charAt(i)>=32 with str.charAt(i)==32

    The the output for "abc23@#$% " will be:

    number of small characters in abc23@#$%  are:3
    number of CAPITAL characters in abc23@#$%  are:0
    number of digits in abc23@#$%  are:2
    number of Spaces in abc23@#$%  are:1
    number of Special characters in abc23@#$%  are:4