美好的一天,我一直在尝试下面的代码:
Good day, I have been trying the below code:
import 'dart:io'; main (){ print ("write your birth year:"); var birthyear = stdin.readLineSync(); var birthyearint = int.parse(birthyear); var age = 2021-birthyearint; print(age); }当我运行它时,出现以下错误:
when I run it I receive the following error:
5:30:错误:参数类型为字符串?"无法分配给参数类型字符串",因为字符串?"是可以为空的,而字符串"不是.var birthyearint = int.parse(birthyear);^
5:30: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't. var birthyearint = int.parse(birthyear); ^
推荐答案该错误是由Dart中的null安全功能引起的,请参见 dart.dev/null-safety .
The error is caused by the null safety feature in Dart, see dart.dev/null-safety.
方法 stdin.readLineSync()的结果为 String?,即它可以是 String ,也可以是空.方法 int.parse()需要一个(非空) String .您应该检查用户是否提供了一些输入,然后可以使用 birthyear!断言该值不为空.更好的是,您应该使用 int.tryParse()来检查用户输入是否为有效整数,例如:
The result of method stdin.readLineSync() is String?, i.e. it may be a String, or it may be null. The method int.parse() requires a (non-null) String. You should check that the user gave some input, then you can assert that the value is non-null using birthyear!. Better still, you should use int.tryParse() to check that the user input is a valid integer, for example:
var birthyearint = int.tryParse(birthyear ?? ""); if (birthyearint == null) { print("bad year"); } else { var age = 2021-birthyearint; print(age); }更多推荐
错误:参数类型为“字符串?"无法分配给参数类型“字符串",因为“字符串?"为可空值,而'String'不是
发布评论