【问题标题】:Dart - How to concatenate a String and my integerDart - 如何连接字符串和我的整数
【发布时间】:2021-05-28 06:01:32
【问题描述】:

如何连接我的 String 和 int 行: print('Computer is moving to ' + (i + 1));print("Computer is moving to " + (i + 1));

我无法弄清楚,因为错误一直说“参数类型'int'不能分配给参数类型'String'

void getComputerMove() {
    int move;

    // First see if there's a move O can make to win
    for (int i = 0; i < boardSize; i++) {
      if (_mBoard[i] != humanPlayer && _mBoard[i] != computerPlayer) {
        String curr = _mBoard[i];
        _mBoard[i] = computerPlayer;
        if (checkWinner() == 3) {
          print('Computer is moving to ' + (i + 1));
          return;
        } else
          _mBoard[i] = curr;
      }
    }

    // See if there's a move O can make to block X from winning
    for (int i = 0; i < boardSize; i++) {
      if (_mBoard[i] != humanPlayer && _mBoard[i] != computerPlayer) {
        String curr = _mBoard[i]; // Save the current number
        _mBoard[i] = humanPlayer;
        if (checkWinner() == 2) {
          _mBoard[i] = computerPlayer;
          print("Computer is moving to " + (i + 1));
          return;
        } else
          _mBoard[i] = curr;
      }
    }
  }

【问题讨论】:

    标签: string flutter dart integer concatenation


    【解决方案1】:

    您可以简单地使用.toString 将您的整数转换为字符串:

    void main(){
         
        String str1 = 'Welcome to Matrix number ';
        int n = 24;
         
        //concatenate str1 and n
        String result = str1 + n.toString();
         
        print(result);
    }
    

    在你的情况下,它会是这样的:

    print("Computer is moving to " + (i + 1).toString()); 
    

    【讨论】:

    • 如果n为null,如何追加null?基本上,实现 Java 功能的最佳方式是什么。打印(“地狱”+x);对于任何类型的 x,如果 x 为 null,则应打印 hellnull。
    • @Priyshrm 如果你想打印 null ,你可以检查语句,如果它是 null ,打印 null : print(x == null ? "null" : x)
    【解决方案2】:

    使用字符串插值:

    print("Computer is moving to ${i + 1}"); 
    

    或者直接调用 toString():

    print("Computer is moving to " + (i + 1).toString()); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-06
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 2011-02-20
      相关资源
      最近更新 更多