Why is this code not working | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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 + " "); } } }

15th Mar 2020, 5:27 AM
Ayan
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
15th Mar 2020, 5:58 AM
A͢J
A͢J - avatar
+ 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.
15th Mar 2020, 7:44 AM
A͢J
A͢J - avatar
+ 2
Thnx bro it worked.
15th Mar 2020, 7:25 AM
Ayan
+ 1
15th Mar 2020, 5:27 AM
Ayan
+ 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?
15th Mar 2020, 7:30 AM
Ayan