I am getting the \"Must be an array type but it resolved to string\" error in my code. It also says that i (in the code below) cannot be resolved to a variable which I don\'
I think you are currently a bit weak at brackets , this is what i understood from your code and corrected it;
public class DNAcgcount{
public double ratio(String dna){
int count=0;
for (int i=0;i<dna.length();i++){
if (dna.charAt(i)== 'c')
count+= 1;
if (dna.charAt(i)=='g')
count+=1;
}
double answer = count/(double)dna.length();
return answer;
}
}
After if we have to close the brackets when what you want in if is finished . I think you wanted count
to be the number of time c
or g
is present in the dna
.
You also did some other mistakes like you have to use 'c'
and 'g'
instead of "c"
and "g"
if you are using .charAt(i)
because it will be treated like a character and then only you can compare .
You may view this link
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
and you may also have a look at works you can do with string like charAt.
Your problem is with syntax dna[i]
, dna
is a string and you access it as it would be an array by []
. Use dna.charAt(i);
instead.
You using String
incorrectly. Instead of accessing via []
use dna.charAt(i)
.
Altough logically a string is an array of characters in Java a String
type is a class (which means it has attributes and methods) and not a typical array.
And if you want to compare a single character to another enclose it with '' instead of "":
if (dna.charAt(i) == 'c')
.
.
It seems like that you have a few problems with the main syntax of basic java functions like loops
or if-else
statement. Click here for a good tutorial on these.
You must correct your for-loop
and your if-statement
:
for(int i=0;i<dna.length();i++){
if(...){
...;
}
if(...){
...;
}
}
Now you wont get the Cant be resolved to a variable... exception
.
Second thing is the usage of your string. You have to use it like this:
for(int i=0;i<dna.length();i++){
if(dna.charAt(i) == 'c'){
count += 1;
}
if(dna.charAt(i) == 'g'){
count += 1;
}
}
Now all your exceptions should be eleminated.
There are two errors:
count should be double or should be casted do double answer = (double)count / dna.length();
and as mentioned above you should replace dna[i] with dna.charAt(i)
Use {}
to define the scope of the loop. Also, as others already pointed out, use charAt
instead of []
and use '
for characters, and use floating point division for the ratio
.
for (int i = 0; i < dna.length(); i++) {
if (dna.charAt(i) == 'c') {
count += 1;
}
if (dna.charAt(i) == 'g') {
count += 1;
}
}
Or a bit shorter, use ||
to or the two clauses together
if (dna.charAt(i) == 'c' || dna.charAt(i) == 'g') {
count += 1;
}