【问题标题】:Error while running the ceylon tutorial code运行锡兰教程代码时出错
【发布时间】:2016-04-14 14:38:48
【问题描述】:

我正在关注这个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?不能分配给字符串

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

【问题讨论】:

    标签: ceylon


    【解决方案1】:

    我是本教程的作者。

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

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

    基本上,问题在于,正如 Lucas Werkmeister 指出的那样,readLine() 返回一个 String?,它等同于 String|Null,因为它可能无法从输入(用户的键盘)中读取任何内容,其中如果你得到null 回来。

    代码示例适用于 Ceylon 1.0.0,因为 readLine() 曾经返回 String

    因此,要编译代码,您需要确保检查您返回的 exists(即不是 null):

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

    当您使用 userX else "" 时,您告诉 Ceylon 如果存在 userX,它应该使用它,如果不存在,则使用 ""。这样,我们总能得到一个String 回...

    整个代码 sn-p 应该如下所示(参见上面链接的示例):

    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!");
    }
    

    感谢您报告错误!希望您喜欢本教程的其余部分。

    【讨论】:

      【解决方案2】:

      process.readLine() 返回一个String?,即如果它可以读取一行则返回String,否则返回null(例如,流结束)。 parseFloat 需要一个非可选的 StringparseFloat(null) 是不允许的。所以你必须assertuserX 存在:

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

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

      两种形式都使userX 成为非可选变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-23
        • 2012-12-13
        相关资源
        最近更新 更多