In: Computer Science
USING JAVA
A little-known fact: According to Pets.WebMD website: For dogs
under 21 pounds in weight, the conversion from a dog’s age to an
equivalent human age is:
1st year: 15 years
2nd year: add 9 years
thereafter: add 4 years for each additional year of the dog’s
age
So, for example, a dog aged 5 would have an equivalent age of
(15+9+4+4+4), or 36 human years old.
Write a lambda expression called convertToHuman, using a standard
functional interface, that will take a given dog and return the
equivalent human age . [Assume dog weighs less than 21 pounds]
If you have any problem with the code feel free to comment.
Program
import java.util.Scanner;
//funtional interface
interface DogToHuman{
public int convertToHuman(int dog);
}
public class Test{
public static void main(String[] args) {
//creating a labda expression
DogToHuman obj = (int dog) -> {
int age = 0;
//calcualting the age of human in dog years
for(int i=1; i<=dog; i++) {
if(i==1)
age +=15;
else if(i==2)
age += 9;
else
age += 4;
}
return age;
};
Scanner sc = new Scanner(System.in);
//taking user input
System.out.print("Enter dogs age: ");
int dog = sc.nextInt();
sc.close();
//displaying output
System.out.println("Human age: "+obj.convertToHuman(dog)+" years");
}
}
Output