Minimum Age Verification GUI C# - c#

i am trying to verify that a customer is at least 25, in order to rent a car.
I believe i have the right code to calculate age in my customer class, but it is not actually verifying it in my code for applying
Code from customer.cs
public int Age
{
get
{
// Get today's date
DateTime currDate = DateTime.Now;
// Get the difference in years
int age = currDate.Year - birthdayPicker.Year;
// Subtract another year if we're before the
// birth day in the current year
if (currDate.Month < birthdayPicker.Month || (currDate.Month == birthdayPicker.Month && currDate.Day < birthdayPicker.Day))
age--;
return age;
}
}
Code From form1.cs (still working on the apply button, but trying to verify age before i move on)
private void applyButton_Click(object sender, EventArgs e)
{
if (myCust.Age >= (25))
{
maketextbox.Text = myVehicle.Make;
modelTextbox.Text = myVehicle.Model;
yearTextbox.Text = Convert.ToString(myVehicle.Year);
vinTextbox.Text = Convert.ToString(myVehicle.Vin);
MessageBox.Show("Congratulations, you have been approved to rent a car!");
}
else
{
MessageBox.Show("You are not old enough to rent a car.");
}

Maybe an error in your comparison code:
// Subtract another year if we're before the
// birth day in the current year
if (currDate.Month < birthdayPicker.Month || (currDate.Month >= birthdayPicker.Month && currDate.Day < birthdayPicker.Day))
age--;
Note: == operator changed to >=

Related

Creating and using Constructors in C# along with Boolean methods

I am having some trouble with constructors in a C# assignment. The first block of code below contains some of the instructions for the assignment. Essentially, as I understand it, I am to create two constructors, one for setting a default date, and another for checking a date from the user. Also, there is a SetDate method that seems to be doing the same thing. These seem redundant, yet according to the assignment instructions, both are required. I am VERY new to object-oriented programming so I am not sure how to "pass" stuff to a constructor or really how to use it and call it in the main method. The second block of code is what I have written so far. All of the date validation methods seem fine. But, I have no idea what to do with the public Date(int M, int D, int Y) constructor and the SetDate method. What should each of these be doing? Also, why am I being instructed to use integer variables M, D, Y when I am also being told to declare Month, Day, and Year above? Any insight that might aid me in understanding how to use this Constructer and how it relates and differs in function from the SetDate method would be greatly appreciated.
//Create a Date Class
//This class holds:
private int Month;
private int Day;
private int Year;
//Include the following constructors/methods. Include others/more if you
//need them.
// Sets date to 1/1/1900
public Date()
// Sets date to user’s input.
// Checks to see the date is valid
// If it isn’t valid, print message and set date to 1/1/1900
public Date(int M, int D, int Y)
// Sets date to user’s input.
// Checks to see the date is valid
// If it isn’t valid, print message and set date to 1/1/1900
public Boolean SetDate(int M, int D, int Y)ere
//******************************************************************************
class Date
{
private int Month;
private int Day;
private int Year;
// Sets date to 1/1/1900
public Date()
{
Month = 1;
Day = 1;
Year = 1900;
}
public Date(int M, int D, int Y)
{
Month = M;
Day = D;
Year = Y;
}
public Boolean SetDate(int M, int D, int Y)
{
int valDate = 0;
Console.WriteLine("You will be prompted to enter three(3) numbers to represent a month, " +
"day, and year. Only dates between 1/1/1900 and 12/31/2100 are valid.");
Console.WriteLine("");
while (valDate < 1)
{
Console.WriteLine("Enter the number for the month.");
M = int.Parse(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("Enter the number for the day.");
D = int.Parse(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("Enter the number for the year.");
Y = int.Parse(Console.ReadLine());
Console.WriteLine("");
ValidateDate();
if (ValidateDate())
{
DisplayDate();
valDate++;
return true;
}
else
{
Console.WriteLine("Please enter a valid date.");
Console.WriteLine("");
Month = 1;
Day = 1;
Year = 1900;
return false;
}
}
return false;
}
// Determines if date is valid.
public Boolean ValidateDate()
{
ValidateMonth();
ValidateDay();
ValidateYear();
if (ValidateMonth() && ValidateDay() && ValidateYear())
{
return true;
}
else
{
return false;
}
}
// Determines if month is valid.
public Boolean ValidateMonth()
{
if (Month >= 1 && Month <= 12)
{
return true;
}
else
{
return false;
}
}
// Determines if year is valid.
public Boolean ValidateYear()
{
if(Year >= 1900 && Year <= 2100)
{
return true;
}
else
{
return false;
}
}
// Determines if day is valid
public Boolean ValidateDay()
{
IsLeapYear();
if(Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8 || Month == 10 || Month == 12)
{
if (Day >= 1 && Day <= 31)
{
return true;
}
else
{
return false;
}
}
else if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
{
if (Day >= 1 && Day <= 30)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && IsLeapYear())
{
if (Day >= 1 && Day <= 29)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && !IsLeapYear())
{
if (Day >= 1 && Day <= 28)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
// Determine if year is a leap year
public Boolean IsLeapYear()
{
if ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0))
{
return true;
}
else
{
return false;
}
}
// Print date to screen in format M/D/Y
public void DisplayDate()
{
Console.WriteLine(ShowDate());
}
public String ShowDate()
{
StringBuilder myStringBuilder = new StringBuilder();
myStringBuilder.AppendFormat("{0} / {1} / {2}", Month, Day, Year);
return (myStringBuilder.ToString());
}
static void Main(string[] args)
{
Date NewDate = new Date();
NewDate.Date();
Console.ReadLine();
}
}
It looks like you've been asked to create a method and a constructor that are doing the same thing. The simple thing to do in this case is to have the constructor call the method.
The only comment I would make about your code is that the problem statement you showed did not require the input to be gathered in the SetDate method. Given the statement it seems like the input from the user would be gathered outside your class.
I don't know what your requirements are for the failure message. That might make sense in it's own method as well.
Here is an example:
public class Date
{
private int Month;
private int Day;
private int Year;
public Date()
{
SetDefaultDate();
}
public Date(int M, int D, int Y)
{
SetDate(M, D, Y);
}
public void SetDate(int M, int D, int Y)
{
if (IsValidDate(M, D, Y))
{
Month = M;
Day = D;
Year = Y;
}
else
{
SetDefaultDate();
}
}
private bool IsValidDate(int M, int D, int Y)
{
// validation logic.. return true if all parameters result in valid date
// false if they do not. If it is an invalid date print the failure message.
return true;
}
private void SetDefaultDate()
{
Month = 1;
Day = 1;
Year = 1900;
}
}
If you want to make some real application using date then i'd suggesting taking look at the DateTime struct in System namespace. That has TryParse function which will return you true or false whether if the input was valid or not.
However it seems like you're doing some programming exercise so in that case my answer would be: It's not very good to have arguments in constructor which could lead to an invalid object - in your case invalid date. That's because once calling the constructor you will have an object in one way or another, except if you throw exception in constructor. Yet if you still want to have it like that then you need to have a property or public variable called "IsValid" in the class/struct which tells if valid date was given with constructor.
Nicer option is follow the DateTime approach - have a public static function which return valid Date object. Like this:
public bool TryParse(int m, int d, int y, out Date date)
{
// validate
// if valid then return Date object like that:
date = new Date()
{
Month = m,
Day = d,
Year = y
};
return true;
// Or like that:
date = new Date(m, d, y);
return true;
// if not valid then return null (because have to return something)
date = null;
return false;
}

Issue with a do while loop

The program below takes the customer age and verify if the customer is eligible to see a certain movie. I am having an issue with CustomerAgeCheck() method. Every time I enter age above 100 or below 0, the loop continues to run infinitely and no result is shown on the label.
protected void okButton_Click(object sender, EventArgs e)
{
AgeVerification();
CostOfTickets();
}
protected int CustomerAgeCheck()
{
int age = int.Parse(Cust1AgeTextBox.Text);
do
{
ageVerificationLabel.Text = String.Format("Please enter the correct age");
} while (age < 0 || age > 100);
return age;
}
protected void AgeVerification()
{
int age = CustomerAgeCheck();
if (Movie3RadioButton.Checked && age < 17)
{
ageVerificationLabel.Text = String.Format("Access denied - you are too young");
}
else if (Movie4RadioButton.Checked || Movie5RadioButton.Checked || Movies6RadioButton.Checked && age < 13)
{
ageVerificationLabel.Text = String.Format("Access deniad - you are too young");
}
else
{
ageVerificationLabel.Text = String.Format("Enjoy your Movie");
}
}
protected void CostOfTickets()
{
int cost;
int totalTickets = int.Parse(CustomerDropDownList.SelectedValue);
cost = totalTickets * 10;
resultLabel.Text = String.Format("Your Total is {0:C}", cost);
}
This is a very bad logic, especially since you're working with a GUI and you have events to help you.
All you have to do is to add a NumericUpDown control, set the min to 0 and max to 100 and then listen to the ValueChanged event.
In this event, you can simply use your above code:
age = (int)NumericUpDownAge.Value;
if (Movie3RadioButton.Checked && age < 17)
{
ageVerificationLabel.Text = String.Format("Access denied - you are too young");
}
else if (Movie4RadioButton.Checked || Movie5RadioButton.Checked || Movies6RadioButton.Checked && age < 13)
{
ageVerificationLabel.Text = String.Format("Access deniad - you are too young");
}
else
{
ageVerificationLabel.Text = String.Format("Enjoy your Movie");
}
You can also disable/enable controls based on the age entered in the NumericUpDown and make your GUI much more interactive and/or self-explanatory.
do
{
ageVerificationLabel.Text = String.Format("Please enter the correct age");
} while (age < 0 || age > 100);
The problem is very simple. It is with the above block of code. you don't have a break condition. When you enter a value above 100 or below 0 into age, its value doesn't changes in the execution of loop. Hence the while loop returns true always (Because the condition is whenever age > 100 and age < 0, repeat the loop) and continues to execute. You should edit it to meet the termination condition according to your need.
When you enter some other value after executing once, as the while loop condition fails it will terminate.

how to get only current date

i have 3 dropdownlist for dd,mm,yyyy.
how to restrict user to enter date greater than current date. ex 7 may 2015.
while giving input 7 may 2015 its giving invalid date. how to restrict user not to select dropdown item greater than current date
protected void btnTest_Click(object sender, EventArgs e)
{
DateTime date1 = DateTime.Now;
string dayNumber = date1.ToString("dd",
CultureInfo.InvariantCulture);
string MonthNumber = date1.ToString("MM",
CultureInfo.InvariantCulture);
string YearNumber = date1.ToString("yyyy",CultureInfo.InvariantCulture);
if (DDLDay.SelectedItem.Text != "DD" && DDLMonth.SelectedItem.Text != "MM" && DDLYear.SelectedItem.Text != "YYYY")
{
if (Convert.ToInt32(DDLYear.SelectedItem.Text) <= Convert.ToInt32(YearNumber))
{
if ((Convert.ToInt32(DDLMonth.SelectedItem.Value) <= Convert.ToInt32(MonthNumber)))
{
if ((Convert.ToInt32(DDLMonth.SelectedItem.Value) <= Convert.ToInt32(MonthNumber)))
{
}
else
{
Response.Write("not valid day ");
return;
}
}
else
{
Response.Write("not valid day");
return;
}
}
else
{
Response.Write("not valid day ");
return;
}
}
else
{
Response.Write("DOB Cannot blank");
}
}
string currentDate = DateTime.Now.ToString("d");
From your current code, you can easily construct a DateTime object and compare that:
DateTime selectedDate = new DateTime( Convert.ToInt32(YearNumber)
, Convert.ToInt32(MonthNumber)
, Convert.ToInt32(DayNumber)
);
if (selectedDate > DateTime.Now)
{
// error
}
You could use the built-in input type="date" in order to have a uniform way the date is formatted. It also supports a maximum date to select.
Why not straighforward > (or >=) between two dates (userInput and limit):
protected void btnTest_Click(object sender, EventArgs e) {
DateTime limit = DateTime.Now.Date;
DateTime userInput = new DateTime(
int.Parse(DDLYear.SelectedItem.Text),
int.Parse(DDLMonth.SelectedItem.Text),
int.Parse(DDLDay.SelectedItem.Text));
//TODO: it's unclear from the question if you want ">" or ">=", put right comparison
if (userInput >= limit) {
Response.Write("not valid day ");
return;
}
...
}

when Date of Birth under 1 year shows 0 Years old I want to convert it to months and days

In my project I am working on patient flow where if the patient only a couple days old then my UI is just showing 0 year old instead of, for example 2 days old or 6 months old.
I want to include this logic to calculate age in months and days of patient.
below is the C# function i am using for calculating age of patient:
public int CalculatedAge
{
get
{
if (Patient.DateOfBirth == null && !Patient.Age.HasValue)
return 0;
else if (Patient.DateOfBirth == null && Patient.Age != null && Patient.Age.HasValue)
return Patient.Age.Value;
else if (Patient.DateOfBirth != null)
return DateTime.Now.ToUniversalTime().Year - Patient.DateOfBirth.Value.Year;
return 0;
}
}
You can create new entities.
enum AgeUnits
{
Days,
Months,
Years
}
class Age
{
public int Value { get; private set; }
public AgeUnits Units { get; private set; }
public Age(int value, AgeUnits ageUnits)
{
Value = value;
Units = ageUnits;
}
}
Then you can use Age as type of CalculatedAge property.
public Age CalculatedAge
{
get
{
if (Patient.DateOfBirth.HasValue)
{
DateTime bday = Patient.DateOfBirth.Value;
DateTime now = DateTime.UtcNow;
if (bday.AddYears(1) < now)
{
int years = now.Year - bday.year;
if (bday > now.AddYears(-years))
years--;
return new Age(years, AgeUnits.Years);
}
else if (bday.AddMonths(1) < now)
{
int months = (now.Months - bday.Months + 12) % 12;
if (bday > now.AddMonths(-months))
months--;
return new Age(months, AgeUnits.Months);
}
else
{
int days = (now - bday).Days;
return new Age(days, AgeUnits.Days);
}
}
else
{
if (Patient.Age.HasValue)
return new Age(Patient.Age.Value, AgeUnits.Years);
else
return null;
}
}
}
public Age CalculatedAge
{
get
{
if (Patient.DateOfBirth == null && Patient.Age != null && Patient.Age.HasValue)
return new Age(Patient.Age.Value);
else if (Patient.DateOfBirth != null)
{
DateTime now = DateTime.UtcNow;
TimeSpan tsAge = now - Patient.DateOfBirth;
DateTime age = new DateTime(tsAge.Ticks);
return new Age(age.Year - 1, age.Month - 1, age.Day - 1);
}
return new Age(0);
}
}
And this is the Age struct:
struct Age
{
public int Years, Months, Days; //It's a small struct, properties aren't necessary
public Age(int years, int months = 0, int days = 0) { this.Years = years; this.Months = months; this.Days = days; }
}
Obviously you can just check the values in with IF statements but a struct for this purpose is cleaner in my opinion.
return new Age(age.Year - 1, age.Month - 1, age.Day - 1); This part is due to the fact that the MinValue of a DateTime object is 01/01/0001 so you need to substract that to get the real age.

Windows Phone countdown app

I am trying to do two things:
On Christmas day, invoke a method whenever the page is navigated to.
After Christmas day, set the christmasDay DateTime to +1 year (so the countdown "resets").
Here is my code:
private void OnTick(object sender, EventArgs e)
{
DateTime christmasDay;
DateTime.TryParse("11/17/13", out christmasDay);
var timeLeft = christmasDay - DateTime.Now;
int x = DateTime.Now.Year - christmasDay.Year;
if (DateTime.Now > christmasDay)
{
if (x == 0)
x += 1;
christmasDay.AddYears(x);
if (DateTime.Now.Month == christmasDay.Month && DateTime.Now.Day == christmasDay.Day)
{
itsChristmas();
}
}
countdownText.Text = String.Format("{0:D2} : {1:D2} : {2:D2} : {3:D2}", timeLeft.Days, timeLeft.Hours, timeLeft.Minutes, timeLeft.Seconds);
}
When I set the date to TODAY, the "itsChristmas()" method works...but I don't actually want it to be invoked on each tick of the countdown. I tried putting it in the constructor of the page but that doesn't work. Any ideas?
The second problem is that if I set the date to a day before today, it gives me negative numbers. I don't know what is wrong with my code that this is happening. :(
Your solution is quite complex. You could solve it like this.
private void OnTick(object sender, EventArgs e)
{
var now = DateTime.Now;
var christmasDay = NextChristmas();
if (now.Date < christmasDay.Date)
{
// it's not christmas yet, nothing happens
}
if (now.Date == christmasDay.Date)
{
// it's christmas, do your thing
itsChristmas();
}
}
private DateTime NextChristmas()
{
var thisYearsChristmas = new DateTime(DateTime.Now.Year, 12, 25);
if (DateTime.Now.Date <= thisYearsChristmas.Date) return thisYearsChristmas;
return thisYearsChristmas.AddYears(1);
}
The if statemements can be written more consise but I elaborated on them to make clear what happens.

Categories

Resources