0

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

4
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by NormR1
0

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 by coil: n/a

0

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

0

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 by Xufyan: n/a

0

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 by NormR1: n/a

0

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

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.