Dart - 如何将字符串和整数拼接

6

如何在以下行中连接字符串和整数:

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;
      }
    }
  }
3个回答

15
使用字符串插值:
print("Computer is moving to ${i + 1}"); 

或者只需调用toString():

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

为什么+运算符没有被重载,以允许这种简单的操作呢?就像在Java中一样。 - Alex

3
您可以直接使用 .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为null,则print("hell"+x)应该打印出hellnull,适用于任何类型的x。 - Priyshrm
@Priyshrm 如果你想打印 null,你可以检查语句是否为 null,如果是,就打印 null:print(x == null ? "null" : x)。 - ParSa

0
 var intValue = Random().nextInt(5)+1;   // 1 <--> 5
 var string = "the nb is $intValue random nb ";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接