Java Day 4: Class vs. Instance




Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print Age is not valid, setting age to 0.. In addition, you must write the following instance methods:
\r\n
# yearPasses() should increase the age instance variable by 1.
# amIOld() should perform the following conditional actions:
* If age<13, print You are young..
* If age>=13 and <18, print You are a teenager..
* Otherwise, print You are old..
\r\n
To help you learn by example and complete this challenge, much of the code is provided for you, but you'll be writing everything in the future. The code that creates each instance of your Person class is in the main method. Don't worry if you don't understand it all quite yet!



  1. import java.io.*;
  2. import java.util.*;
  3. public class Solution {
  4. static class Person {
  5. private int age;
  6. public Person(int initialAge) {
  7. // Add some more code to run some checks on initialAge
  8. if (initialAge > 0) {
  9. age = initialAge;
  10. } else {
  11. System.out.println("Age is not valid, setting age to 0.");
  12. age = 0;
  13. }
  14. }
  15. public void amIOld() {
  16. // Write code determining if this person's age is old and print the correct statement:
  17. if (age < 13) System.out.println("You are young.");
  18. else if (age < 18) System.out.println("You are a teenager.");
  19. else System.out.println("You are old.");
  20. }
  21. public void yearPasses() {
  22. // Increment this person's age.
  23. age++;
  24. }
  25. }
  26. public static void main(String[] args) {
  27. Scanner sc = new Scanner(System.in);
  28. int T = sc.nextInt();
  29. for (int i = 0; i < T; i++) {
  30. int age = sc.nextInt();
  31. Person p = new Person(age);
  32. p.amIOld();
  33. for (int j = 0; j < 3; j++) {
  34. p.yearPasses();
  35. }
  36. p.amIOld();
  37. System.out.println();
  38. }
  39. sc.close();
  40. }
  41. }
download android app

Popular HackerRank Java Solutions








codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube