【发布时间】: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;
}
假设0 或1 也可以是integer 类型,所以nextBoolean() 会抛出异常。那么从java中的命令行读取boolean输入的最佳方法是什么。
【问题讨论】:
-
当我们将布尔值评估为字符串时,我们会检查字符串的第一个字母是否为 Y、y 或 1 为真,否则为假。
标签: java parsing boolean command-line-arguments