0
public class Person{
    private String email;

    public Person() throws Exception {
        setEmail("info@yourmail.com");
    }

    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("example@mail.com");
        }catch(Exception e) {
            fail("Parameterized constructor failed");
        }
    }

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

Sapehi
  • 133
  • 1
  • 8
  • 4
    Instead of `email.substring(email.length() - 4) != ".com"` you should use `email.endsWith(".com")` – QBrute Nov 08 '21 at 17:18
  • 3
    Other comments are valid but also - do not use `==` or `!=` for string comparison: https://stackoverflow.com/a/8484699/2711811. –  Nov 08 '21 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. – Seelenvirtuose Nov 08 '21 at 17:22
  • ...yes, there is definitely more to fix, and not to forget: https://rules.sonarsource.com/java/RSPEC-1699 – xerx593 Nov 08 '21 at 17:25
  • (email.substring(email.length() - 4) != ".com" && email.substring(email.length() - 3) != ".nz") is returning true mate – Deepanshu Rathi Nov 08 '21 at 17:27

0 Answers0