Logically I believe that when I run my code anyone between 0 and 11 should be assigned ageGroup = children
, 12 to 19 should be ageGroup = teenager
, 20 to 31 ageGroup = young adult
, and 31+ ageGroup = adult
. I've tried different things such as if (age < 0 && age > 11)
but that returns the same results. Basically my question is am I using the logical operators correctly for what I am trying to do?
import java.util.ArrayList;
import java.util.List;
public class Person implements Comparable<Person> {
private String name;
private int age;
private String ageGroup;
public Person(String name, int age) {
this.name = name;
this.age = age;
if (name == null || name == "") {
throw new IllegalArgumentException("name cannot be null or empty");
}
if (age < 0) {
throw new IllegalArgumentException("age cannot be negative");
}
List<String> inList = new ArrayList<>();
if (age == 0 && age <= 11) {
ageGroup = "children";
} else if (age == 12 || age <= 19) {
ageGroup = "teenagers";
} else if (age == 20 || age <= 31) {
ageGroup = "young adults";
} else if (age >= 32) {
ageGroup = "adults";
}
inList.add(ageGroup);
}
@Override
public int compareTo(Person o) {
if (age < o.age) {
return -1;
} else {
if (age > o.age) {
return 1;
} else {
return name.compareTo(o.name);
}
}
}
@Override
public boolean equals(Object o) {
if (o != null) {
if (o == this) {
return true;
}
if (getClass() == o.getClass()) {
Person other = (Person) o;
if (compareTo(other) == 0) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
return String.format(
"Person [name=%s,age=%d,group=%s]",
name, age, ageGroup);
}
}
This code is supposed to return [name=Fiona,age=0,group=children]
but it returns [name=Fiona,age=11,group=teenagers]