1

我正在关注这个教程,它给了我这个代码:

"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? 不能分配给 String

我已经复制/粘贴了这段代码,但仍然是相同的消息。

4

2 回答 2

3

我是教程的作者。

非常抱歉此示例代码不再起作用(它适用于 Ceylon 1.0.0,见下文)。

我已经在教程中修复了它,并在 Ceylon Web IDE 中创建了一个可运行的示例,您可以使用它来尝试一下。

基本上,问题在于,正如 Lucas Werkmeister 指出的那样,readLine()返回的 aString?相当于String|Null因为它可能无法从输入(用户的键盘)中读取任何内容,在这种情况下你会null回来。

该代码示例与 Ceylon 1.0.0 一起使用,因为readLine()用于返回String.

因此,要编译代码,您需要确保检查您返回的内容exists(即 is NOT null):

value userX = process.readLine();
value x = parseFloat(userX else "");

当你这样做时userX else "",你告诉 Ceylon 如果userX存在,它应该使用 that,如果不存在,则使用""。这样,我们总能得到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-14T06:29:59.967 回答
1

process.readLine() returns a String?, that is, a String if it could read a line, or null if not (for example, end of stream). parseFloat requires a non-optional String: parseFloat(null) is not allowed. So you have to assert that userX exists:

assert (exists userX = process.readLine());

or

value userX = process.readLine();
assert (exists userX);

Both forms make userX a non-optional variable.

于 2016-04-13T21:50:43.520 回答