gpt4 book ai didi

java - Boolean.valueOf() 的良好用法

转载 作者:太空宇宙 更新时间:2023-11-04 06:29:05 30 4
gpt4 key购买 nike

我有关于使用 Boolean.valueOf(String) 的问题。在我的代码中,用户将通过输入 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";
}

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

最佳答案

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

您还应该考虑对字符串文字(例如 "true""false")调用 equalsIgnoreCase,而不是对变量调用 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";

关于java - Boolean.valueOf() 的良好用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26368120/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com