Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
Why is this code not working
I was completing the Pig Latin challenge but was not able to complete it. I am not able to understand what is wrong with the code. Someone please help me with the code import java.util.*; import java.lang.*; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); String sentence = input.nextLine(); Scanner checker = new Scanner(sentence); String s = ""; while(checker.hasNext()) { s=checker.next(); s=s+s.substring(0,1); s=s.concat("ay"); s=s.replace(s.substring(0,1), ""); System.out.print(s + " "); } } }
5 Answers
+ 5
Your s = s.replace(s.substring(0,1), ""); is replacing both substring value.
You have to replace first character not to character. Using this logic your are replacing character not first character of String.
use replaceFirst instead of replace
+ 4
Ayan When you use that statement it replace all characters in String with substring value. For example this String "anant" when you do like this:
"anant". replace ("anant".substring(0, 1), "");
"anant".replace("a", ""); //here both a will be replace by "", but you want to replace only first character of String "anant". Right?
So here you need to use replaceFirst.
"anant". replaceFirst ("a", ""); // here only first character will be replace.
+ 2
Thnx bro it worked.
+ 1
https://www.sololearn.com/coach/16?ref=app
The link of the challenge
+ 1
What did you exactly meant by replacing both substring values when I was using earlier statement
s=s.replace(s.substring(0,1), "") ;
What was the problem with this statement?