【问题标题】:The good usage of Boolean.valuesOf()Boolean.valueOf() 的良好用法
【发布时间】:2014-10-14 18:47:51
【问题描述】:

我对@9​​87654321@ 的使用有疑问。在我的代码中,用户将通过输入truefalse 来回答问题。然后字符串应该被转换为boolean

public String setCorrespondingAuthor ()
{
    String respons = "true";
    do
    {
        System.out.print("Is s/he the corresponding author? (true/false)");
        respons = sc.next();
        sc.nextLine();
    } while (!respons.equalsIgnoreCase("true")
            && !respons.equalsIgnoreCase("false"));
    boolean flag = Boolean.valueOf(respons);
    if (!flag)
    {
        return "not the corresponding author";
    }
    return "the corresponding author";
}

现在,它工作正常。问题是在输出中,它在处理之前提示了两次问题。

【问题讨论】:

  • 这可能不是您使用Boolean.valueOf 的问题。我认为您的输入处理有问题。首先输入“true”然后输入“false”来测试。你的输出是“真”还是“假”的输出?
  • @trw 该条件基本上是“当响应不等于 true 也不等于 false”。
  • sc.nextLine(); 立即请求第二个输入,不是吗?
  • 正如@Arkanon 所说,错误在您的do/while
  • @Freiheit:当我输入“true”然后“false”时,我得到了答案,因为输出为“false”(来自第二行)。

标签: java boolean value-of


【解决方案1】:

问题是您从用户输入中读取了两次:sc.next()sc.nextLine()。您应该只读取一次并将该值存储在您的 respons 变量中。

您还应该考虑在字符串文字(例如"true""false")而不是变量上调用equalsIgnoreCase,因为变量可能是null,导致NullPointerException

String respons = "true";
do
{
    System.out.print("Is s/he the corresponding author? (true/false)");
    respons = sc.nextLine();
} while (!"true".equalsIgnoreCase(respons)
        && !"false".equalsIgnoreCase(response));
return Boolean.valueOf(respons) ? "the corresponding author" : "not the corresponding author";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多