Recursive Methods ; StringIndexOutOfBoundsException
This is a code to count how many times a character appeared in a String...
It has to be done recursively...
Code :
import java.io.*;
public class Methods{
public static void main(String args []) throws IOException{
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (instream);
System.out.println("Please insert a passage");
String passage = br.readLine();
System.out.println("Please insert character");
String crc = br.readLine();
char x = crc.charAt(0);
System.out.println("This passage has this character " + crccount(passage, x));
}
public static int crccount(String passage, char x){
int count = 0;
int z = passage.length();
if (z == 0){
return 0;
}
if (passage.charAt(z) == x){
count++;
}
return count + crccount(passage.substring(0, z-1), x);
}
}
RUNTIME:
Please insert a passage
medo
Please insert character
e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at Methods.crccount(Methods.java:459)
at Methods.main(Methods.java:451)
Any suggestions?
Re: Recursive Methods ; StringIndexOutOfBoundsException
change only 1 line
Code Java:
package test;
import java.io.*;
public class Methods{
public static void main(String args []) throws IOException{
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (instream);
System.out.println("Please insert a passage");
String passage = br.readLine();
System.out.println("Please insert character");
String crc = br.readLine();
char x = crc.charAt(0);
System.out.println("This passage has this character " + crccount(passage, x));
}
public static int crccount(String passage, char x){
int count = 0;
int z = passage.length();
if (z == 0){
return 0;
}
else if (passage.charAt(z-1) == x){//just change this line
count++;
}
return count + crccount(passage.substring(0, z-1), x);
}
}
I hope it will work
Re: Recursive Methods ; StringIndexOutOfBoundsException
THANKS ALOT MAN...
I HONESTLY APPRECIATE IT... :D
Re: Recursive Methods ; StringIndexOutOfBoundsException
I didn't notice charAt method starts at 0... Silly mistakes :@
Thanks alot though ;)