Skip to content

Instantly share code, notes, and snippets.

@sadgirltory
Created April 30, 2020 16:57
Show Gist options
  • Save sadgirltory/4718bb50b69e6ca17ef29934a90320e7 to your computer and use it in GitHub Desktop.
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 …
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