-4

I am writing code that translates a DNA sequence! The program imports a string called shortDNA (for example ATCGGA) and has to translate it (specifically to TAGCCT), but for some reason it gives the shortDNA string that it imports(in this case ATTCGGA)! what is wrong with my code?

for (int i = 0; i < shortDNA.length(); i++) {
            char ch = shortDNA.charAt(i);
            if (ch=='A'){
                ch='T';
            }
            else if (ch=='T'){
                ch='A';
            }
            else if (ch=='G'){
                ch='C';
            }
            else if (ch=='C'){
                ch='G';
            }
        }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Gamio
  • 1
  • 5

1 Answers1

0

Instead of setting a character variable which is discarded, I assume you want to use this character to build a new String.

StringBuilder sb = new StringBuilder();
for (char ch : dna.toCharArray()) {
    switch (ch) {
        case 'A': sb.append('T'); break;
        case 'T': sb.append('A'); break;
        case 'G': sb.append('C'); break;
        case 'C': sb.append('G'); break;
    }
}
String dna2 = sb.toString();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130