Ekaterina1234 Ekaterina1234 - 7 months ago 8
Java Question

The output of this loop should be less than 1, but I get very large numbers

This program is supposed to count the number of characters "c" and "g" in genes in the DNA string and then take that number and divide it by the length of each gene. The number of cs and gs is always < gene.length(), therefore the output should be something like 0.65555, 0.35657 etc, but I get large numbers like 141, etc. Not sure what is wrong with this loop.

public void testfile(){
String dnaTest = "aaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaacccttaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctaaccctcacccttctaact";


int counter = 0;
for(String gene : s1.data()) {

for (char cORg : gene.toCharArray()) {
if ((cORg == 'c') || (cORg == 'g')) {
counter ++;
}

System.out.print(gene +" ");

}
float cgRatioGenes = counter/gene.length();
System.out.println("cgRatio: " + cgRatioGenes);
}


If you spot the error, let me know. Thanks!

EDIT

Even without the parentesis at the end of the DNA string and with the closing bracket, the loop was not producing the results I expected. Therefore, it is not off topic.

Answer

Two problems:

First, you never reinitialize counter when you start the loop again. Move that declaration inside the loop so that each repetition starts with a counter of zero.

If you make that change, all your results will be zero though, because you're diving two integers, which will truncate the results. Cast one to float, so that it keeps the decimal part. See this question for more information on the problem

for(String gene : s1.data()) {
    int counter = 0; //Moved inside the for loop, so that it always starts at 0
    for (char cORg : gene.toCharArray()) {
        if ((cORg == 'c') || (cORg == 'g')) {
            counter ++;
        }

        System.out.print(gene +" ");
    }

    //Floating point division, instead of integer division
    float cgRatioGenes =  ((float)counter)/gene.length(); 
    System.out.println("cgRatio:  " + cgRatioGenes);
}