Created
April 30, 2020 16:57
-
-
Save sadgirltory/4718bb50b69e6ca17ef29934a90320e7 to your computer and use it in GitHub Desktop.
Day 4: Write a Person class with an instance variable, , and a constructor that takes an integer, , as a parameter. The constructor must assign to after confirming the argument passed as is not negative; if a negative argument is passed as , the constructor should set to and print Age is not valid, setting age to 0.. In addition, you must write …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
public class Person { | |
private int age; | |
public Person(int initialAge) { | |
// Add some more code to run some checks on initialAge | |
if(initialAge<0){ | |
age = 0; | |
System.out.println("Age is not valid, setting age to 0."); | |
} | |
else{ | |
age = initialAge; | |
} | |
} | |
public void amIOld() { | |
// Write code determining if this person's age is old and print the correct statement: | |
if(age<13) | |
{ | |
System.out.println("You are young."); | |
} | |
else if(age>=13 && age<18) | |
{ | |
System.out.println("You are a teenager."); | |
} | |
else | |
{ | |
System.out.println("You are old."); | |
} | |
} | |
public void yearPasses() { | |
// Increment this person's age. | |
age++; | |
} | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int T = sc.nextInt(); | |
for (int i = 0; i < T; i++) { | |
int age = sc.nextInt(); | |
Person p = new Person(age); | |
p.amIOld(); | |
for (int j = 0; j < 3; j++) { | |
p.yearPasses(); | |
} | |
p.amIOld(); | |
System.out.println(); | |
} | |
sc.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment