You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Dart中如何获取整数类型的用户输入?

Dart 获取整数用户输入空安全报错解决方案

报错原因

该报错是Dart空安全机制的强制校验导致的:

Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.

stdin.readLineSync() 用于读取控制台输入,返回值是可空类型String?,当读取失败(如用户触发EOF、无有效输入)时会返回null;而int.parse()要求传入的参数必须是非空的String类型,二者类型不匹配因此触发编译错误。

解决方案

  • 方法1:非空断言(仅适用确定有有效输入的场景)
    如果你能确保程序运行时一定会有用户输入合法内容,可以通过!非空断言告诉编译器该返回值一定不为空:

    import 'dart:io'; // 注意必须导入io库才能使用stdin
    
    int calculate(){
        int x = int.parse(stdin.readLineSync()!);
        int y = int.parse(stdin.readLineSync()!);
        return x + y;
    }
    

    注意:如果实际运行时readLineSync返回null,该写法会抛出运行时空指针异常。

  • 方法2:空值设置默认值
    为了避免运行时异常,可以用空合并运算符??给空输入设置默认的 fallback 字符串,比如无输入时默认取0:

    import 'dart:io';
    
    int calculate(){
        int x = int.parse(stdin.readLineSync() ?? '0');
        int y = int.parse(stdin.readLineSync() ?? '0');
        return x + y;
    }
    
  • 方法3:全场景合法性校验(最严谨)
    同时处理空输入、非整数格式输入的场景,避免所有潜在异常:

    import 'dart:io';
    
    int calculate(){
        // 处理x的输入
        int x = 0;
        String? inputX = stdin.readLineSync();
        if (inputX != null) {
          int? parseResult = int.tryParse(inputX);
          if (parseResult != null) {
            x = parseResult;
          }
        }
    
        // 处理y的输入
        int y = 0;
        String? inputY = stdin.readLineSync();
        if (inputY != null) {
          int? parseResult = int.tryParse(inputY);
          if (parseResult != null) {
            y = parseResult;
          }
        }
    
        return x + y;
    }
    

内容的提问来源于stack exchange,提问作者Nuh Yamin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:06:00