Replace of pii roblem

import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
String str=sc.next();
String ans=replace(str,0);
System.out.println(ans);

	}
}
public static String replace(String str,int i){
	if(i>str.length()-1)
	return "";
	if(i==str.length()-1)
	return str.substring(i);
	String res="";
	String ros;
	if(str.charAt(i)=='p' && str.charAt(i+1)=='i'){
		res=res.substring(0,i)+"3.14";
		ros=replace(str,i+2);
	}
	else{
		res+=str.charAt(i);
		ros=replace(str,i+1);
	}
	return res+ros;

	}
	}
compilation successful but getting runtime error,please correct my code

@karthik1989photos,
Don’t pass i as an argument. It will throw an exception because str.length will change at every iteration. You are on the right path though, just a few changes needed.

Suggested approach:

  • Traverse the string. At each instance check whether substring starting from index 0 till index 2 is same as β€œpi”.
  • If so , obtain the result for remaining string from index 2 i.e. s.substring(2) recursively . Store this result in say β€˜ros’ . Now return β€œ3.14” + ros.
  • If however , it was not so , obtain the result for the remaining string starting from index 1 and add s[0] to it i.e. return s[0] + ros.

import java.util.*;
public class Main
{
public static String pi(String str)
{
if (str.length() <= 1)
{
return str;
}
if (str.charAt(0) == β€˜p’ && str.charAt(1) == β€˜i’)
{
return β€œ3.14” + pi(str.substring(2));
} else
{
return str.charAt(0) + pi(str.substring(1));
} }
public static void main(String args[])
{
try{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++){
String s=sc.next();
System.out.println(pi(s));
}} catch(Exception e)
{
System.out.println(e);
}
}
i tried but showing errors at return statement plz correct my code

@karthik1989photos,
https://ide.codingblocks.com/s/278795 I submitted the same code and its giving a correct answer. Maybe you have missed a closing bracket at the end. The code is correct.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.