我遵循这个tutorial,它给了我这个代码:
"Run the module `hello.ceylon`."
shared void run() {
process.write("Enter a number (x): ");
value userX = process.readLine();
value x = parseFloat(userX);
process.write("Enter a number (y): ");
value userY = process.readLine();
value y = parseFloat(userY);
if (exists x, exists y) {
print("``x`` * ``y`` = ``x * y``");
} else {
print("You must enter numbers!");
}
}但它给了我这样的信息:
参数必须可以赋值给parseFloat的参数字符串: String?不能赋值给字符串
我已经复制/粘贴了这段代码,但仍然是相同的消息。
发布于 2016-04-14 14:30:00
我是本教程的作者。
我非常抱歉这个示例代码不再工作了(它在Ceyl1.0.0上工作,见下文)。
我已经在教程中修复了它,并在Ceylon Web IDE中创建了一个runnable sample,您可以使用它来尝试。
基本上,问题是,正如Lucas Werkmeister指出的那样,readLine()返回一个等同于String|Null的String?,因为它可能无法从输入(用户的键盘)中读取任何内容,在这种情况下,您将获得null。
代码示例适用于Ceylon1.0.0,因为readLine()过去常常返回一个String。
因此,对于要编译的代码,您需要确保检查您得到的exists (即.不是null):
value userX = process.readLine();
value x = parseFloat(userX else "");当你做userX else ""时,你告诉锡兰,如果userX存在,它应该使用它,如果不存在,使用""。这样,我们总能得到一个String。
整个代码片段应该如下所示(参见上面链接的示例):
process.write("Enter a number (x): ");
value userX = process.readLine();
value x = parseFloat(userX else "");
process.write("Enter a number (y): ");
value userY = process.readLine();
value y = parseFloat(userY else "");
if (exists x, exists y) {
print("``x`` * ``y`` = ``x * y``");
} else {
print("You must enter numbers!");
}感谢您报告错误!希望您喜欢本教程的其余部分。
发布于 2016-04-14 05:50:44
process.readLine()返回一个String?,如果可以读取一行,则返回String;如果不能读取一行,则返回null (例如,流结束)。parseFloat需要非可选的String:不允许使用parseFloat(null)。所以你必须通过assert确认userX的存在:
assert (exists userX = process.readLine());或
value userX = process.readLine();
assert (exists userX);这两种形式都使userX成为非可选变量。
https://stackoverflow.com/questions/36609961
复制相似问题