I am suppose to create a recursive method that will compress a DNA sequence. For example;
DNA.compress("GGCcCTtttTT") => "G2C3T6"
but my code keeps giving me an
java.lang.ArrayIndexOutOfBoundsException: -1
at DNA.compress(DNA.java:41)
at DNA.compress(DNA.java:44)
at DNA.compress(DNA.java:34)
at Test.main(Test.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.ru nCommand(JavacCompiler.java:272)
for the Test Case tgg
my code ispublic static String compress(String dna){ String dnaUpper = dna.toUpperCase(); char[] dnaArray = dnaUpper.toCharArray(); int len = dnaArray.length; if(dnaUpper.length() > 1){ System.out.println("The char at the end is " + dnaArray[len-1]); if((dnaArray[len-1] >= 'A') && (dnaArray[len-1] <= 'Z')){ //if the last entry is a letter if(dnaArray[len-1] == dnaArray[len-2]){ //if the last 2 entries match return compress(dna.substring(0, dna.length() - 2) + dnaUpper.charAt(dna.length()-1) + "2"); }else{ //if the last 2 entries don't match return compress(dna.substring(0, dna.length() - 2) + dna.charAt(len-1)); } }else{ //if the last entry is a number if((dnaArray[len-2] >= 'A') && (dnaArray[len-2] <= 'Z')){//if the second last entry is a letter if(dnaArray[len-2] == dnaArray[len-3]){ //if the second and third last entires match return compress(dna.substring(0,dna.length()-3) + (Integer.parseInt(""+dnaArray[dnaArray.length -1]) + 1)); } else{ //if the second and third last entries dont match return compress(dna.substring(0,dna.length()-3) + dna.substring(dna.length()-2)); } }else{//if the second last entry is not a letter if(dnaArray[len-3] == dnaArray[len-4]){ //if the third last and 4th last entries match return compress(dna.substring(0,dna.length()-4) + Integer.parseInt(dna.substring(dna.length()-3)) + 1); }else{ //third and 4th last entries don't match return compress(dna.substring(0,dna.length()-4) + dna.substring(dna.length()-3)); } } } }else{ return dnaUpper; } }
if you could help me out, I'd really appreciate it.
Thanks