Recursion /String problem
So I am new to java and been practicing recursion with recursion practices from codingbat
The problem im working on is this
CodingBat Java Recursion-1 changePi
and here's my code for it
Code java:
public class changePi {
public String changeToPi(String str){
String total = "";
if(str.length() == 0)
return "";
if (str.substring(0, 4) == "3.14")
{
total = "pi";
total = total + changeToPi(str.substring(4));
}
else if (str.substring(0, 4) != "3.14")
{
total = str.substring(0,1);
total = total + changeToPi(str.substring(1));
}
return total;
}
public static void main (String args[]){
changePi um = new changePi();
um.changeToPi("3.14ihiuhui");
}
}
problem is that whenever I try to run it i get a String index out of range error
Been looking over the problem over and over again and can't spot what I did wrong. Would appreciate some help.
Re: Recursion /String problem
Quote:
i get a String index out of range error
Please copy the full text of the error message and post it here.
Re: Recursion /String problem
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.substring(Unknown Source)
at changePi.changeToPi(changePi.java:12)
at changePi.changeToPi(changePi.java:23)
at changePi.changeToPi(changePi.java:23)
at changePi.changeToPi(changePi.java:23)
at changePi.changeToPi(changePi.java:23)
at changePi.changeToPi(changePi.java:23)
at changePi.changeToPi(changePi.java:23)
at changePi.changeToPi(changePi.java:23)
at changePi.changeToPi(changePi.java:23)
at changePi.main(changePi.java:33)
Re: Recursion /String problem
Quote:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.substring(Unknown Source)
at changePi.changeToPi(changePi.java:12)
At line 12 the index to the String is past the end of the String
To see what is happening, add a println() statement at line 11 that prints the String and its length.
The printout will show you what String the code is working with.
The test of the String length should make sure the length is >= 4 vs == 0
Re: Recursion /String problem
ok got it, will check
sweet, got it to work! thx
public class changePi {
public String changeToPi(String str){
String total = "";
if (str.length() < 4 && !str.equals("3.14"))
{
return str;
}
if (str.length() >= 4)
{
if (str.substring(0, 4).equals("3.14"))
{
total = "pi";
total = total + changeToPi(str.substring(4));
}
else if (!str.substring(0, 4).equals("3.14"))
{
total = str.substring(0,1);
total = total + changeToPi(str.substring(1));
}
}
return total;
}
public static void main (String args[]){
changePi um = new changePi();
String newPi;
newPi = um.changeToPi("3.14ih3.14.56ih3ih");
System.out.println(newPi);
}
}