1

我有一个关于使用的问题Boolean.valueOf(String)true在我的代码中,用户将通过输入或来回答问题false。然后应该将 String 转换为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";
}

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

4

1 回答 1

1

The problem is that you're reading twice from user input: sc.next() and sc.nextLine(). You should only read once and store that value in your respons variable.

You should also consider calling equalsIgnoreCase on String literals( such as "true" , "false") and not on variables, because variables might be null, resulting into a 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";
于 2014-10-14T19:27:33.517 回答