uk21
import java.util.Scanner;
class MyDate {
int day, month, year;
// Copy code
public MyDate(int day, int month, int year) throws InvalidDateException {
if (!isValidDate(day, month, year)) {
throw new InvalidDateException("Invalid date!");
}
this.day = day;
this.month = month;
this.year = year;
}
private boolean isValidDate(int day, int month, int year) {
// check if day is valid for the month
if (day < 1 || day > 31) {
return false;
}
if (month == 2) {
// check if day is valid for February
if (day > 29) {
return false;
}
// check for leap year
if (day == 29) {
if (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0)) {
return false;
}
}
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
// check if day is valid for months with 30 days
if (day > 30) {
return false;
}
}
// check if month is valid
if (month < 1 || month > 12) {
return false;
}
return true;
}
public void displayDate() {
System.out.println(day + "/" + month + "/" + year);
}
}
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter date (dd mm yyyy): ");
int day = sc.nextInt();
int month = sc.nextInt();
int year = sc.nextInt();
try {
MyDate date = new MyDate(day, month, year);
date.displayDate();
} catch (InvalidDateException e) {
System.out.println(e.getMessage());
}
}
}
class InvalidDateException extends Exception {
public InvalidDateException(String message) {
super(message);
}
}
Q2) Create an employee class(id,name,deptname,salary). Define a default and
parameterized constructor. Use ‘this’ keyword to initialize instance variables.
Keep a count of objects created. Create objects using parameterized constructor
and display the object count after each object is created. (Use static member
and method). Also display the contents of each object.
SOLUTION:
import java.util.*;
class Employee {
int id;
String name;
String deptname;
double salary;
static int count;
Employee(){
id=0;
name="Name";
deptname="Comp sci";
salary=20000;
}
Employee(int id , String name , String deptname , double salary){
this.id=id;
this.name=name;
this.deptname=deptname;
this.salary=salary;
count++;
}
void display() {
System.out.println("[ID:" + id + " NAME: " + name + " DEPAMAENT NAME: "
- deptname + " SALArY: " + salary + " ]");
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many Employees ");
int number = sc.nextInt();
Employee[] emp = new Employee[number];
for(int j=0; j<number; j++)
{
System.out.println("Enter ID ");
int id = sc.nextInt();
System.out.println("Enter Name ");
String name = sc.next();
System.out.println("Enter Department name");
String deptname = sc.next();
System.out.println("Enter Salary");
int salary = sc.nextInt();
emp[j] = new Employee(id,name,deptname,salary);
}
for(int j=0; j<number; j++)
{
emp[j].display();
}
System.out.println("\nThere are total "+Employee.count+" Employees.");
}
}