Home > Net >  clear string before method is called again?
clear string before method is called again?

Time:11-16

How do I fix this? (I am not allowed to change anything in my main method) I can't put String = ""; at the top of my method since it is recursive, but what else can I do?

public static String DNA = "";

   return DNA;
}

CodePudding user response:

Just build the string up through your return statements:

NOTE: You may need to change your logic to make sure you handle all possible outcomes that would add to your string before you return

public static String generateDNA(int f, int m) {
   if(f==0 && m==0) {
      return "";
   }
   else if(f==0 && m!=0) {
      return "A"   generateDNA(f,m/2);
   }
   else if(f!=0 && m==0) {
      return "T"   generateDNA(f/2,m);
   }
   else if(f!=0 && m!=0) {
      if((f%2==0 && m%2==0)||(f%2!=0 && m%2!=0)) {
         if(f>m) {
         return "GT"   generateDNA(f/2, m/2);
      }
      if(f<m) {
         return "GA"   generateDNA(f/2,m/2);
      }
         if(f==m) {
         return "GC"   generateDNA(f/2,m/2);
      }
   } else{
         if(f%2!=0) {
         return "TC"   generateDNA(f/2,m/2);
      }
         if(m%2!=0) {
         return "AC"   generateDNA(f/2,m/2);
      }
   }
   }
}

CodePudding user response:

This is because your DNA variable is static, I would make that a parameter which would look something like this

   public static String generateDNA(String DNA, int f, int m) {
   if(f==0 && m==0) {
      return "";
   }
   else if(f==0 && m!=0) {
      DNA= "A"  DNA;
      generateDNA(DNA,f,m/2);
   }
   else if(f!=0 && m==0) {
      DNA = "T"   DNA;
      generateDNA(DNA,f/2,m);
   }
   else if(f!=0 && m!=0) {
      if((f%2==0 && m%2==0)||(f%2!=0 && m%2!=0)) {
         if(f>m) {
         DNA = "GT"   DNA;
         generateDNA(DNA,f/2, m/2);
      }
         if(f<m) {
         DNA = "GA"   DNA;
         generateDNA(DNA,f/2,m/2);
      }
         if(f==m) {
         DNA = "GC"   DNA;
         generateDNA(DNA,f/2,m/2);
      }
   }
      else{
         if(f%2!=0) {
         DNA = "TC"   DNA;
         generateDNA(DNA,f/2,m/2);
      }
         if(m%2!=0) {
         DNA = "AC"   DNA;
         generateDNA(DNA,f/2,m/2);
      }
   }
   }

   return DNA;
}

OR

Before you call this method for the first time, call

your_class_name_here.DNA = "";
  • Related