Find the Bug😖 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Find the Bug😖

I'm trying to code a method that takes a single character as an argument and returns the increment of that character. e.g incrementChar('a') outputs 'b' and so on. The code below works fine without the first if statement which is if the input character is a symbol which is not included in the string then it should return the character. But when I add the first if statement as it is below, it does returns the character if it is a symbol but it no longer increments if it is an alphabetic character. I have tried all I could but it doesn't seem to work. What's the problem? function incrementChar(char) { var alphabets = 'abcdefghijklmnopqrstuvwxyz', next = ''; for(let i = 0; i < alphanumeric.length; i++) { if(char != alphanumeric[i]) { next = char; break; } if(char == alphanumeric[i]) { next = alphanumeric[i + 1]; break; } return next; } }

4th Oct 2020, 8:09 PM
Logos
Logos - avatar
2 Answers
+ 4
HI Edewor, that is because you are instantaneously jumping off the loop if you are not choosing 'a'. The first 'if' statement is not doing what you assume. In the first iteration ( i=0) it will check if your character is != 'a'. That's true for all cases but 'a'. So it will print that character and breaks out the complete loop with that 'c'. Also, your complete logic is a little bit odd. Do something else here. function incrementChar(char) { let alphabets = 'abcdefghijklmnopqrstuvwxyz'; let result = alphabets.indexOf(char); if (result===-1) { //your char is not in the alphabet given. return char; } else if (result === alphabets.length-1) { //what ever should happen, when 'z' is the char. } else { return alphabets[result+1]; } } I hope I did not made a syntax typo, I typed that on the fly. Have a nice day
4th Oct 2020, 8:31 PM
Zen Coding
Zen Coding - avatar
+ 1
Zen Coding Thank you so much. I understand now. If not for your comment I wouldn't have known. I am a beginner. Programming is crazy but I love it😊. Thanks again.
4th Oct 2020, 10:03 PM
Logos
Logos - avatar