Replace all Ļ€ problem

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);
    String s=sc.nextLine();
	System.out.println(pi(s));
}
catch(Exception e){System.out.println(e);}}

}
What is wrong with this code.

Your code is working just fine but you need to read the question again. You forgot to input n and print out the output for each string input.

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.nextLine(); System.out.println(pi(s)); }} catch(Exception e){System.out.println(e);}} }

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.nextLine(); System.out.println(pi(s)); }} catch(Exception e){System.out.println(e);}} } still it is showing wrong answer

just write the scn.next()
while taking the string input

nextline() will take the new line as the input.
so just write the scn.next()

1 Like