i've made the following program that count how many times the input character is appeared in a string.

import java.io.*;
class strngcls{
public static void main (String args[])throws IOException{
String s1,s2;
char ch;
InputStreamReader ir = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (ir);
System.out.println ("Type any Sentence: ");
s1=br.readLine();
ch = 'X';
System.out.println (charcount(s1,ch));
}
static int charcount (String st, char c){
int count=0;
for (int i=0;i<st.length(); i++)
if (c==st.charAt(i))
	count++;
	return count;
	}
}

This program is counting how many times a capital 'X' is appeared in a string , i want my program to count capital and small both....i applied is.UpperCase and is.LowerCase but it is not working

Member Avatar for coil

isLowerCase() returns a boolean value, but does not modify the String. Use toLowerCase(), which returns a modified String:

String s="aBcDeF";
s=s.toLowerCase();

Another approach would be to have the desired char as both uppercase and lowercase and compare each char in the String against both of them

still nt working

import java.io.*;
class strngcls{
public static void main (String args[])throws IOException{
String s1,s2;
char ch;
InputStreamReader ir = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (ir);
System.out.println ("Type any Sentence: ");
s1=br.readLine();
ch = 'X';
System.out.println (charcount(s1,ch));
}
static int charcount (String st, char c){
int count=0;
for (int i=0;i<st.length(); i++)
if (c=Character.toLowerCase(st.charAt(i)))
	count++;
	return count;
	}
}

Error:

strngcls.java:16: incompatible types
found : char
required: boolean
if (c=Character.toLowerCase(st.charAt(i)))
^
1 error

The compiler is looking for a boolean in the if condition, but your code provides a char:
c=Character.toLowerCase(st.charAt(i))
The above statement returns the value of c from the assignment (=) statement
To return a boolean, change the assignment (=) to an equality test (==)

Also, if your test char is 'X' then lower-casing the String will guarantee no matches.
To do a case-insensitive match, convert both the String and the test char to the same case (lower or upper, doesn't matter, as long as they are both the same).

convert both the string ?? what do you mean ???

convert both the String and the test char to the same case

Compare 'X' against "XASDFASDF" or 'x' against 'xasdfasdf' . Note the two being compared are the same case.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.