这是我练习运动的代码。我想将键入的颜色更改为小写,以确保不会出现任何错误。但是我现在的方法给了我一个关于for循环的错误:“ for循环中使用的类型化字符串必须实现可迭代的dart”。帮助吗?
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));
}
}
答案 0 :(得分:0)
这是答案。
您在这里的错误是givenColors.toString().toLowerCase()
givenColors()
是一个列表,不能像在for循环中给出的那样将列表转换为字符串。在下面的代码中,我们从列表中获取一个值,然后转换为小写。
此行color.toLowerCase()
将值转换为小写,因为color
在每次迭代中都包含来自列表的单个值。
更新代码
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));
}
}
答案 1 :(得分:0)
givenColors.toString()
将您的列表转换为字符串;所以不能迭代;
您可以采取的解决方案很少;
List colorsLowercase = [];
for (var color in givenColors) {
colorsLowercase.add(color.toLowerCase())
...
}
或者像@pskink建议的
givenColors.map((c) => c.toLowerCase())