将double转换为boolean的问题

时间:2019-02-24 02:58:33

标签: java boolean

我正在使用多个类以及GUI的Java类中的一个项目进行工作(不确定该信息是否相关)。我和我的小组伙伴遇到了一个问题。我们有一个Validator类,该类应验证“ SSN”,但我们不断收到错误消息:

java:146: error: incompatible types: double cannot be converted to boolean
                    if(Validator.isValidSSN(jTextFieldEmpSSN)){

现在显然是java:146了。我们每个班级的代码是:

employeeUI类(显示错误的类):

private void jButtonEnterActionPerformed(java.awt.event.ActionEvent evt) 
{
        Employee e=new Employee();

        if(Validator.isValidName(jTextFieldEmpFirst)){
            if(Validator.isValidName(jTextFieldEmpLast)){
               if(Validator.isValidEmail(jTextFieldEmpEmail)){
                    if(Validator.isValidSSN(jTextFieldEmpSSN)){
        e.setFirstName(jTextFieldEmpFirst.getText());
        e.setLastName(jTextFieldEmpLast.getText());
        e.setEmailAdd(jTextFieldEmpEmail.getText());
        e.setSSN(Integer.parseInt(jTextFieldEmpSSN.getText()));
}}}}

,isValidSSN的Validator类为:

public static double isValidSSN(JTextField textfield)
{
    double number = 0;
    boolean inRange = false;
    while(!inRange)
    {
        number = Double.parseDouble(textfield.getText());
        if (number >= 100000000 && number <= 999999999) 
        {
            inRange = true;

        } else {}
    } 

    return number;
}

一段时间以来,我们一直在努力解决这个问题,但是却无所适从。我们错过了什么吗?我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

If I ask, "Is 123-45-6789" a valid SSN?" you wouldn't reply "123456789.0", would you? You'd give me a yes or a no. By returning double your method is doing the former. It's responding with a number instead of an answer to the question.

A good rule of thumb is that methods starting with is or has should return booleans. "Is this a valid SSN?" is a yes/no question, so isValidSSN should return the programming equivalent of yes/no.

public static boolean isValidSSN(JTextField textfield)

There are a couple of other design points here:

  • The loop isn't necessary. The SSN is either valid or it isn't.

  • A text field is not itself an SSN. It holds some text, and that text is the SSN. Rather than taking a text field and looking up the text in the field with getText(), it'd be better to have isValidSSN take the text directly. Let the caller extract the text from the text field.

    In broader terms this is known as the single responsibility principle. Every method should ideally do just one thing.

Result:

public static boolean isValidSSN(String ssn) {
    double number = Double.parseDouble(ssn);

    if (number >= 100000000 && number <= 999999999) {
        return true;
    }
    else {
        return false;
    }
}

P.S. If I don't mention it someone will surely comment that the if and else blocks aren't necessary; one can return the if result directly. They would be right, though I consider it a bit of an advanced trick. It would look like so:

public static boolean isValidSSN(String ssn) {
    double number = Double.parseDouble(ssn);
    return number >= 100000000 && number <= 999999999;
}