Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

occurence count of character in a string

Hi,

I am trying below challenge

http://codingbat.com/prob/p173784

I wrote as below

public boolean stringE(String str) {

int counter = 0;
for( int i=0; i<str.length(); i++ ) {
    if( str.charAt(i) == 'e' ) {
        counter++;
    } 
    if(1<=counter<=3){
    return true;
    }
    return false;
}
  
}

Open in new window


I am getting error as

Compile problems:


Error:      if(1<=counter<=3){
         ^^^^^^^^^^^^^
The operator <= is undefined for the argument type(s) boolean, int


see Example Code to help with compile problem


How to fix this error and improve my program to make it work. Please advise
Avatar of Haris Dulic
Haris Dulic
Flag of Austria image

You can get rid of the error by using :

 if(1<=counter && counter<=3){

Open in new window

Avatar of gudii9

ASKER

Error is gone. What is the difference between

if(1<=counter && counter<=3){

and

if(1<=counter<=3){

public boolean stringE(String str) {

int counter = 0;
for( int i=0; i<str.length(); i++ ) {
    if( str.charAt(i) == 'e' ) {
        counter++;
    } 
    if(1<=counter && counter<=3){
    return true;
    }
    return false;
}
  return false;
}

Open in new window


My code looks like above i have few test cases failing as below

Expected      Run            
stringE("Hello") → true      false      X         
stringE("Heelle") → true      false      X         
stringE("Heelele") → false      false      OK         
stringE("Hll") → false      false      OK         
stringE("e") → true      true      OK         
stringE("") → false      false      OK         


Please advise
Change it to :

for( int i=0; i<str.length(); i++ ) {
    if( str.charAt(i) == 'e' ) 
        counter++;
    }
    return(1<=counter && counter<=3);

Open in new window

Avatar of gudii9

ASKER

public class Test10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		stringE("hello");
	}

	
	public static boolean stringE(String str) {

		int counter = 0;
		for( int i=0; i<str.length(); i++ ) {
		    if( str.charAt(i) == 'e' ) {
		        counter++;		    
		    if(1<=counter && counter<=3){
		    return true;
		    }
		  //  return false;
		}
		  return false;
		}
		return false;
	}
}

Open in new window



i wrote as above. I wonder what is wrong in that. Please advise
ASKER CERTIFIED SOLUTION
Avatar of Haris Dulic
Haris Dulic
Flag of Austria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanx 4 axxepting