带字符串返回的布尔方法

时间:2014-08-18 01:56:59

标签: java string boolean

在这个作业中,我必须做一个谓词方法,打印一个问题,然后等待一个问题。如果用户输入no,则该方法应返回false,如果用户输入yes,则该方法应返回true。我做到了!但在这部分我有问题:如果用户输入另一个东西,程序必须说“错误的答案”之类的东西,并重复问题。我不能返回一个字符串,因为它是一个布尔方法,我不知道如何解决这个问题。 谢谢!!

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

}
}

2 个答案:

答案 0 :(得分:2)

首先StrBoo是一个糟糕的方法名称。我会称之为getAnswer(),并使用像

这样的东西
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;
}

答案 1 :(得分:0)

这种程序的正确设计是抛出异常。这是一个例子:

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()
        }
    }
}