DNA project

Hello everyone! :smirk:

I am working on the DNA Project and I reached a problem. There are three items within an ArrayList. And when I run it through a for-each-loop, only one result shows. I think I messed up somewhere.

import java.util.ArrayList;
public class DNA{
// DNA Sequencing
  public static void main(String[] args){
    ArrayList<String> dnaSamples = new ArrayList<String>();
    dnaSamples.add("ATGCGATACGCTTGA");
    dnaSamples.add("ATGCGATACGTGA");
    dnaSamples.add("ATTAATATGTACTGA");
    String dna;
    int length;
    for(String sample : dnaSamples){
      dna = sample;
      length = dna.length();
      if(length % 3 == 0){
        if(sample.substring(0, 3) == "ATG"){
          if(sample.substring(length - 3) == "TGA"){
            System.out.println("Conditions satisfied");
          }
        }
      }else{
        System.out.println("Sample " + dnaSamples.indexOf(sample) + " is an Invalid DNA Sequence!");
      }
    }
    
  }
}

Any help would be appreciated!

You’ve properly added them to your array. If you drop a simple println statement you’d get:

ATGCGATACGCTTGA
ATGCGATACGTGA
Sample 1 is an Invalid DNA Sequence!
ATTAATATGTACTGA

Which means that you have to check your conditionals.
For example you can write:
System.out.println(length % 3 == 0);
to check if that’s ever registering as true. And the same for the other conditionals.

1 Like

I checked, the if(sample.substring(0, 3) == "ATG"){ part isn’t getting through. I see no reason though.

1 Like

Use the equals() method when comparing strings in Java, since == is comparing objects technically (not values).

Example:
if(sample.substring(0, 3).equals("ATG")) should work.

Some light reading: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java