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

问题描述 投票:1回答:2

这是我进行运动练习的代码。我想将键入的颜色更改为小写,以确保不会出现任何错误。但是我现在的方式给了我一个关于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));
  }
}

flutter dart
2个回答
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));
  }
}

0
投票

givenColors.toString()将您的列表转换为String;因此无法迭代;

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

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

或建议使用@pskink

givenColors.map((c) => c.toLowerCase())
© www.soinside.com 2019 - 2024. All rights reserved.