+ Start a Discussion
Arnold Joseph TodasArnold Joseph Todas 

CharAt() method Error

Why i am getting an error on method charAt(i)? this is a piglatin word exercise.
here is my code:
String s = 'happy';
s = s.toUpperCase();

Integer l = s.length();
Integer pos = -1;
String str;
Integer i;

for( i = 0; i < l; i++){
    str = s.chartAt(i);
    if(str == 'A' || str == 'E' || str == 'I' || str == 'O' || str == 'U'){
        pos = i;
        break;
    }
}
if(pos != -1){
    String a = s.substring(pos);
    String b = s.substring(0,pos);
    String pig = a + b + 'ay';
    System.debug('' + pig);
}else
    System.debug('Eat bulaga');
Very appreciate if you can help me thaks!
AJ
 
logontokartiklogontokartik
Hi,
The charAt method on line 10 is missplled and it does not return a string, but returns an integer value which is a ASCII notation of the character. 

Below is corrected version. You can easily optimize the code using other String methods, but the below should work.
 
s = s.toUpperCase();	
		Integer l = s.length();
		Integer pos = -1;
		Integer charAscii;
		Integer i;
        String pig;

		for( i = 0; i < l; i++){
    		charAscii = s.charAt(i);
    		if(charAscii == 65 || charAscii == 69 || charAscii == 73 || charAscii == 79 || charAscii == 85){
        		pos = i;
        		break;
    		}	
		}
		if(pos != -1){
    		String a = s.substring(pos);
    		String b = s.substring(0,pos);
    		pig = a + b + 'ay';
    		System.debug('' + pig);
        }else {
    		System.debug('Eat bulaga');
    	}

Thank you

 
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior

Hello,

logontokartik is right!

And if you don't feel comfortable using ASCII codes you can try this way instead:

String s = 'happy';
s = s.toUpperCase();

Integer l = s.length();
Integer pos = -1;
String str;
Integer i;

for( i = 0; i < l; i++){
    if( i == 0) 
    	str = s.substring(i, i);
    else 
        str = s.substring(i-1, i);
    
    if(str == 'A' || str == 'E' || str == 'I' || str == 'O' || str == 'U'){
        pos = i;
        break;
    }
}
if(pos != -1){
    String a = s.substring(pos);
    String b = s.substring(0,pos);
    String pig = a + b + 'ay';
    System.debug('' + pig);
}else
    System.debug('Eat bulaga');