Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Boolean.valuesOf()的良好用法_Java_Boolean_Value Of - Fatal编程技术网

Java Boolean.valuesOf()的良好用法

Java Boolean.valuesOf()的良好用法,java,boolean,value-of,Java,Boolean,Value Of,我有一个关于Boolean.valueOf(String)用法的问题。在“我的代码”中,用户将通过输入true或false来回答问题。然后字符串应转换为布尔值 public String setCorrespondingAuthor () { String respons = "true"; do { System.out.print("Is s/he the corresponding author? (true/false)"); re

我有一个关于
Boolean.valueOf(String)
用法的问题。在“我的代码”中,用户将通过输入
true
false
来回答问题。然后字符串应转换为
布尔值

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";
}

现在,一切正常。问题是,在输出中,在处理问题之前,它会提示问题两次。

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

您还应该考虑调用字符串代码(例如<代码> > true > ,<代码> > false 而不是变量,因为变量可能是<代码> null <代码>,从而导致<代码> Null PoExtExtry

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";

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