如何将列表更改为小写?在 for 循环中不断出现错误



这是我练习练习的代码。我想将键入的颜色更改为小写,以确保不会有任何错误。但是我现在的方式在 for 循环上给了我一个错误"for 循环中使用的类型字符串必须实现可迭代的飞镖"。帮助?

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));
}
}

这是答案。 你的错误在这里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));
}
}

>givenColors.toString()将您的列表转换为字符串; 所以它不能迭代;

您可以采取的解决方案很少;

List colorsLowercase = [];
for (var color in givenColors) {
colorsLowercase.add(color.toLowerCase())
...
}

或者像@pskink建议的那样

givenColors.map((c) => c.toLowerCase())

最新更新