Day 4 :Class vs. Instance
Solution In Java 8:
import java.io.*;import java.util.*;
public class Person {
private int age;
public Person(int initialAge) {
this.age = initialAge;
if(age<0)
{
age = 0;
System.out.println("Age is not valid, setting age to 0.");
}
}
public void amIOld() {
String str = "";
if(age < 13)
{
str = "You are young.";
}
else if(age >= 13 && age < 18)
{
str = "You are a teenager.";
}
else
{
str = "You are old.";
}
System.out.println(str);
}
public void yearPasses() {
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();
}
}
Solution In Python 3:
class Person:
def __init__(self, initialAge):
if initialAge > 0:
self.age = initialAge
else:
print("Age is not valid, setting age to 0.")
self.age = 0
def amIOld(self):
if self.age < 13:
print("You are young.")
elif self.age < 18:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
self.age += 1
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
Very knowledgeable post thank you for sharing Python Online Training Bangalore
ReplyDelete