-3

So I wrote code where you enter someone's first name, last name and whatnot and their age. Then someone ele's first name and so on. Then I wanted to compare their ages so I wrote

 if (age != age2){
         System.out.println (firstName + "is the same age as" + firstName);
         }else{
             System.out.println ( "They are different ages");

             }

         }

That tells me that they're the same age which is fine. However, I want to add something where it compares age to age 2 and comes back with "is 22 years older than" and so on. I'm not sure how to do this and I've looked all around and not found things on how to do this.

2 Answers2

0

You may be looking for something like below. You can add conditions accordingly. This is just an example.

 public static void main(String[] args){
        int ageOne = 22;
        int ageTwo = 45;

        if((ageOne - ageTwo) == 0){
            System.out.print("Person with ageOne and ageTwo are same age");
        }else if((ageOne - ageTwo) > 0){
            System.out.print("Person with ageOne is " +(ageOne - ageTwo) + " years olders than ageTwo");
        }else if((ageOne - ageTwo) < 0){
            System.out.print("Person with ageTwo is " +(ageTwo - ageOne) + " years older than ageOne");
        }else{
            //error condition.
        }
    }
0

Java is object oriented language practice in OO.

public class Person {
private String fullName;
private int age;

public String getFullName() {
    return fullName;
}
public void setFullName(String fullName) {
    this.fullName = fullName;
}

public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
}


public class ProblemSolution {

public static void main(String[] args) {
    Person p1 =  new Person();
    p1.setAge(18);
    p1.setFullName("sunny leone");

    Person p2 = new Person();
    p2.setFullName("Matty");
    p2.setAge(16);

    printMessage(p1,p2);

}

private static void printMessage(Person p1, Person p2) {
    int a = p1.getAge() - p2.getAge();
    if(a < 0) {
        System.out.println(p1.getFullName() +" is "+ -(a) +" years younger than "+  p2.getFullName() );
    } else if( a > 0) {
        System.out.println(p1.getFullName() +" is "+ (a) +" years older than "+  p2.getFullName() );
    } else {
        System.out.println(p1.getFullName() +" is same age  "+  p2.getFullName() );
    }
}

}