【问题标题】:How to take a integer as input in Dart? [duplicate]如何在 Dart 中将整数作为输入? [复制]
【发布时间】:2021-03-29 12:56:07
【问题描述】:

我试图在 Dart 中使用整数作为输入,正如许多来源所建议的那样。

import 'dart:io';

  void main() {
  int n = int.parse(stdin.readLineSync());
}

但是当我尝试运行时显示以下错误消息(Visual Studio Code 也在问题中显示它):

错误:参数类型“字符串?”不能分配给参数类型“字符串”,因为“字符串?”可以为空,而 'String' 不是。

现在如何将整数或双精度数作为输入? (我使用的是 Dart SDK 版本:2.12.2(稳定))

【问题讨论】:

标签: dart


【解决方案1】:

您在 Dart 2.12.2 中默认使用 Null Safety。

readLineSync() 返回一个可空值的String?

但是,int.parse() 采用不能为 null 的 String,因为 Null 安全性。这就是错误所在。

为了解决这个问题,你必须在使用它之前检查是readLineSync() return null。

import 'dart:io';

void main() {
  String? s = stdin.readLineSync();
  if (s != null){
    int n = int.parse(s);
    print(n); // Or do whatever you want with your n value
  }
}

【讨论】:

  • 在执行此操作时 !=null 条件未得到满足,因此我无法获取所需的输入。
  • 它对我有用。只需在解析后添加print(n);即可。
  • 不幸的是,我的工作没有。
  • 如果你添加一个带有打印的else条件,它会通过吗?
  • 是的,在这种情况下,使用其他条件。
【解决方案2】:

一个处理intdoubleString的例子:

import 'dart:io';

void main() {
  String? s = stdin.readLineSync();
  if (s != null) {
    if (int.tryParse(s) != null) {
      int n = int.parse(s);
      print('int $n'); // Or do whatever you want with your int value
    } else if (double.tryParse(s) != null) {
      double d = double.parse(s);
      print('double $d'); // Or do whatever you want with your double value
    } else {
      print('string "$s"'); // Or do whatever you want with your string value
    }
  }
}

【讨论】:

  • 难道不能像我们在 C/C++、python 等中那样接受输入吗?
  • Dart readLineSync 方法是否可以与 C gets 和 Python input 函数相媲美?我不知道任何与 C scanf 函数等效的 Dart。
  • 但在我的情况下,当我使用 readLineSync() 进行输入时,输入的格式是字符串?当我使用 int.parse() 将其更改为整数时,总是会出现问题中提到的错误,因此我无法将输入作为整数以及双精度和字符串。只有字符串?可以输入类型。
  • 方法readLineSync()返回的是用户输入的字符串,或者为null,所以类型为String?。由您的代码来解释字符串。您可以将其解释为您想要的任何内容,上面的代码解析字符串以查看它是 int 还是 double,但您可以编写代码来匹配任何输入序列。 (包pub.dev/packages/string_scanner 可以在这里提供帮助。)
猜你喜欢
  • 2020-11-14
  • 2020-02-17
  • 1970-01-01
  • 2021-02-18
  • 2022-07-22
  • 2021-12-07
  • 2020-08-24
相关资源
最近更新 更多