【问题标题】:Parsing boolean input in java from command line.从命令行解析 java 中的布尔输入。
【发布时间】:2018-03-03 08:04:14
【问题描述】:

您好,我需要从命令行读取 boolean 值。我是 Java 新手,所以在进行了一些基本搜索之后,我编写了以下代码。问题是如果我使用nextBoolean() 函数,我会得到inputmismatchexception。所以我不得不编写if 条件检查并对值进行硬编码。

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.print("Enter Boolean Value: ");
    String value = s.nextLine();
    //Boolean myBoolVal = s.nextBoolean(); // Throws InputMismatchException if anything other than true/false is entered.
    Boolean myBoolVal = false;
    if (value.equalsIgnoreCase("true") || value.equals("1"))
    myBoolVal = true;
}

假设01 也可以是integer 类型,所以nextBoolean() 会抛出异常。那么从java中的命令行读取boolean输入的最佳方法是什么。

【问题讨论】:

  • 当我们将布尔值评估为字符串时,我们会检查字符串的第一个字母是否为 Y、y 或 1 为真,否则为假。

标签: java parsing boolean command-line-arguments


【解决方案1】:

从技术上讲,您只能在命令行中输入文本。方法nextBoolean 只接受文本"true" and returns true 并接受文本"false" and returns false。如果你想将文本“0”解释为假或“1”解释为真或“f”解释为假或“t”解释为真等等,那么你必须编写自己的代码,就像你已经完成的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    相关资源
    最近更新 更多