This is a code to count how many times a character appeared in a String...
It has to be done recursively...
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?