0
public class Person{
    private String email;

    public Person() throws Exception {
        setEmail("[email protected]");
    }

    public Person(String email) throws Exception {
        setEmail(email);
    }
  
  public void setEmail(String email) throws Exception {
        if (email.indexOf('@') == -1 || (email.substring(email.length() - 4) != ".com" && email.substring(email.length() - 3) != ".nz")) {
        throw new Exception("[ERROR] Email not correct");
    } else {
        this.email = email;
        }
    }

However, initialization always fails when I test it this way:

void init() {
        try{
            person = new Person("[email protected]");
        }catch(Exception e) {
            fail("Parameterized constructor failed");
        }
    }

I am not able to figure why. Why is this happening?

5
  • 4
    Instead of email.substring(email.length() - 4) != ".com" you should use email.endsWith(".com") Commented Nov 8, 2021 at 17:18
  • 3
    Other comments are valid but also - do not use == or != for string comparison: stackoverflow.com/a/8484699/2711811. Commented Nov 8, 2021 at 17:21
  • 2
    @xerx593 No, this is wrong. He wants to throw the exception if both is true (not ending with ".com" AND not ending with ".nz"). So, his logic is ok, his tools are not. Commented Nov 8, 2021 at 17:22
  • ...yes, there is definitely more to fix, and not to forget: rules.sonarsource.com/java/RSPEC-1699 Commented Nov 8, 2021 at 17:25
  • (email.substring(email.length() - 4) != ".com" && email.substring(email.length() - 3) != ".nz") is returning true mate Commented Nov 8, 2021 at 17:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.