I’m taking a Coursera Java course but am stuck here for days now.
The two methods belong to the same class, and very similar other than the return type and one additional variable in the method that doesn’t work.
This DOES NOT work (the code is compiled but not executed on BlueJ):
public int countAllGenes(String dna) {
int count = 0;
int startIndex = 0;
while (true) {
String gene = findGene(dna, startIndex);
if(gene.isEmpty()) {
break;
}
count = count + 1;
startIndex = dna.indexOf(gene, startIndex) + gene.length();
}
return count;
}
But this works:
public void printAllGenes(String dna) {
int startIndex = 0;
while (true) {
String gene = findGene(dna, startIndex);
if (gene.isEmpty()) {
break;
}
System.out.println(gene);
startIndex = dna.indexOf(gene, startIndex) + gene.length();
}
}
I’m confused because the code that doesn’t work is literally part of the answer key found online. (I had to look it up because I was not sure if there’s something wrong with my code or not.) Could anyone kindly help? Lots of thanks!
Both methods should be executed successfully.
slee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.