1

I have a question about the use of Boolean.valueOf(String). In my code the user will answer a question by entering either true or false. Then the String should be converted to a 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";
}

Right now, it works okay. The problem is that in the output, it prompts the question twice before treat it.

jwir3
  • 6,019
  • 5
  • 47
  • 92
samia
  • 31
  • 4
  • 2
    This is probably not a problem from your use of `Boolean.valueOf`. I think you have an issue with your input handling. Test this by first entering "true" then enter "false". Is your output the output for "true" or "false"? – Freiheit Oct 14 '14 at 18:51
  • @trw that condition basically reads "while the response is not equal to true and not equal to false". – Bobulous Oct 14 '14 at 18:52
  • 2
    `sc.nextLine();` requests a second input immediately, does it not? – njzk2 Oct 14 '14 at 18:53
  • As @Arkanon said, the error is in your `do/while` – erp Oct 14 '14 at 18:59
  • @ Freiheit: when I enter "true" then "false" I get the answer as the output was "false"(from the second line). – samia Oct 14 '14 at 19:15
  • @ njzk2: I get the same problem even if I deleted sc.nextLine(); – samia Oct 14 '14 at 19:17
  • @erp I am not saying there is anything wrong with that `while` test condition. That condition is equivalent to: `while (!(respons.equalsIgnoreCase("true") || response.equalsIgnoreCase("false"))` and it tells the loop to keep going until either "true" or "false" is entered. – Bobulous Oct 14 '14 at 19:46

1 Answers1

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";
Daniel
  • 1,861
  • 1
  • 15
  • 23