Can someone help me with these codes. I'm trying to validate the date(e.g if the users entered February 31, which is not an existing date, the program should give an exception output). Aside from this, we are required to do our own exception. Thank you!

class MyDateException extends Exception
{}
public class TestMyDate 
{
	public static void main(String args[])
		{
			boolean isValid = true;
			
			MyDate [] m = new MyDate[args.length];
			
			for (int i=0;i<args.length;i++)
		{
				String s[]=args[i].split(",");
			try{
				int x=Integer.parseInt(s[0]);
				int y=Integer.parseInt(s[1]);
				int z=Integer.parseInt(s[2]);
				m[i] = new MyDate(x,y,z);
				}
			catch(MyDateException mde)
			{
					System.out.println("Invalid!");
				}
			}
		
		for(MyDate a: m)
		{
			System.out.println(a);
		}
		
		}
		
}
class MyDate
{
	private int date;
	private int month;
	private int year;

	public MyDate(int date, int month, int year)
	{
		isValid(date, month, year);
	}
	public boolean isValid(int d, int m, int y)
	{
		if(m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12 && y > 0)
			{
				if(d>=31)
				{
					setDate(date);
					setMonth(month);
					setYear(year);
				}	
				else
					return false;
			}
	
	}
	public void setDate(int date)
	{
		this.date = date;
	}
	public void setMonth(int month)
	{
		this.month = month;
	}
	public void setYear(int year)
	{
		this.year = year;
	}
	
	public int getDate()
	{
		return date;
	}
	public int getMonth()
	{
		return month;
	}
	public int getYear()
	{
		return year;
	}
	
	public String toString()
	{
		return getDate() + ", " + getMonth() + ", " + getYear();
	}

}

Recommended Answers

All 2 Replies

The exception must be in its own class - file. So you will have 3 files:
MyDateException.java
TestMyDate.java
MyDate.java

In the constructor of MyDate if the isValid method returns false, you will throw the exception.

Apart from that you are ok. Although you will need to correct the logic in the isValid method.

Thanks! I'll edit it now!:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.