首页 > 解决方案 > 如何从 Ballerina 的命令行中读取 int?

问题描述

any choice = io:readln("Enter choice 1 - 5: ");

我似乎无法将输入转换为 int。

检查和匹配都给出相同的错误

var intChoice = <int>choice;
match intChoice {
    int value => c = value;
    error err => io:println("error: " + err.message);
}

c = check <int>choice;

error: 'string' cannot be cast to 'int'

我查看了https://ballerina.io/learn/by-example/type-conversion.html并研究了https://ballerina.io/learn/api-docs/ballerina/io.html#readln但没有运气。

我究竟做错了什么?

标签: ballerina

解决方案


似乎这是any -> int转换中的错误。

如果使用 将选择变量类型更改为string或将变量定义语句更改为赋值语句var,则两种方法都可以使用。请参考以下示例。

import ballerina/io;

function main(string... args) {
    // Change the any to string or var here.
    string choice = io:readln("Enter choice 1 - 5: ");
    int c = check <int>choice;
    io:println(c);

    var intChoice = <int>choice;
    match intChoice {
        int value => io:println(value);
        error err => io:println("error: " + err.message);
    }
}

更新- 正如@supun 在下面提到的,这不是any->int转换中的错误,而是我不知道的实现细节。


推荐阅读