BeatoJeronimo
BeatoJeronimo

Reputation: 37

Boolean method with string returns

in this homework i have to do a predicate method that prints a question and then waits for a question. if the user enters no, the method should return false, if the user enters yes the method should return true. I have done that ! but in this part i have problems: if the user enters another thing the program must say something like "wrong answer" and repeat the question. I can't return a string because is a boolean method and i dont know how to resolve this. Thank you!!

import acm.program.ConsoleProgram;
public class YesNo extends ConsoleProgram{
    public void run () {
   String answer = readLine ("would you like instructions? ");
   println (StrBoo (answer));
}


private boolean StrBoo(String answer){
    if (answer.equals("yes")) {
        return true;
    } else if (answer.equals("no")) {
        return false;
    } else { 
    return false;
    }   

}
}

Upvotes: 2

Views: 7379

Answers (2)

Carlo
Carlo

Reputation: 1579

The correct design for such kind of program is to throw an exception. Here is an example:

import acm.program.ConsoleProgram;

public class YesNo extends ConsoleProgram 
{
    class WrongAnswerException extends Exception
    {
    }

    public void run ()
    {
        try
        {
            String answer = readLine("would you like instructions? ");
            println(StrBoo(answer));
        }
        catch(WrongAnswerException e)
        {
            println("You have to write yes or no!")
        }
    }

    private boolean StrBoo(String answer) throws WrongAnswerException
    {
        if ("yes".equals(answer))
        {
            return true;
        }
        else if ("no".equals(answer))
        {
            return false;
        }
        else
        {
            throw new WrongAnswerException()
        }
    }
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201527

First StrBoo is a poor method name. I would call it getAnswer(), and use something like,

private static boolean getAnswer() {
  while (true) {
    String answerStr = readLine ("would you like instructions? ");
    answerStr = (answerStr != null) ? answerStr.trim() : "";
    if ("yes".equalsIgnoreCase(answerStr)) {
      return true;
    } else if ("no".equalsIgnorecase(answerStr)) {
      return false;
    } else {
      System.out.println("Wrong answer");
    }
  }
  return false;
}

Upvotes: 2

Related Questions