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

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

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

Edited 6 Years Ago by coil: n/a

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

Edited 6 Years Ago by Xufyan: n/a

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 (==)

Edited 6 Years Ago by NormR1: n/a

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 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.

This article has been dead for over six months. Start a new discussion instead.