Reputation: 41
This is the code I have for an exercise on exercism. I want to change the colours typed to lower case just to be sure there won't be any errors. But the way I have now gives me an error on the for loop "the typed string used in the for loop must implement iterable dart". Help?
void main(){
ResistorColorDuo obj = new ResistorColorDuo();
obj.result(['Orange','Black']); //I want something that would make these colours lower case so there's no error if someone types it with upper case
}
class ResistorColorDuo {
static const COLOR_CODES = [
'black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'grey', 'white',];
void result(List<String> givenColors) {
String numbers = '';
for (var color in givenColors.toString().toLowerCase()) {//But this throws an error "the type string used in the for loop must implement iterable dart"
numbers = numbers + COLOR_CODES.indexOf(color).toString();
}
if (givenColors.length != 2)
print ('ERROR: You should provide exactly 2 colors');
else
print (int.parse(numbers));
}
}
Upvotes: 2
Views: 1619
Reputation: 1391
Here is the answer.
Your mistake was here givenColors.toString().toLowerCase()
the givenColors()
is a list and list can't be converted to string as you are giving in a for loop. In the below code we take a single value from the list and then convert to the lower case.
This line color.toLowerCase()
converts the value to the lower case as color
contains a single value from the list on each iteration.
Updated Code
void main(){
ResistorColorDuo obj = new ResistorColorDuo();
obj.result(['Orange','Black']); //I want something that would make these colours lower case so there's no error if someone types it with upper case
}
class ResistorColorDuo {
static const COLOR_CODES = [
'black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'grey', 'white',];
void result(List<String> givenColors) {
String numbers = '';
for (var color in givenColors) {//But this throws an error "the type string used in the for loop must implement iterable dart"
numbers = numbers + COLOR_CODES.indexOf(color.toLowerCase()).toString();
}
if (givenColors.length != 2)
print ('ERROR: You should provide exactly 2 colors');
else
print (int.parse(numbers));
}
}
Upvotes: 2
Reputation: 11881
givenColors.toString()
converts your list to String; so it can't be iterated;
There are few solutions you can take;
List colorsLowercase = [];
for (var color in givenColors) {
colorsLowercase.add(color.toLowerCase())
...
}
Or like @pskink suggested
givenColors.map((c) => c.toLowerCase())
Upvotes: 1