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.
Related
I'm just starting to learn C# and I'm trying to create a really simple program about knowing the DayOfWeek of a specific Date. The continue keyword in the do-while loop doesn't work for error checking.
I have tried doing another way of error checking, by including the conditions directly inside the while loop, but I'm curious why the continue doesn't work.
class Program
{
static void Main(string[] args)
{
int yearInput, monthInput, dateInput;
Console.WriteLine("We can tell you any day of any date");
bool correctInput;
//the problem starts at dateInput request (the third do while loop)
do { Console.WriteLine("\nSet a year :");
correctInput = int.TryParse(Console.ReadLine(), out yearInput);
if (!correctInput)
{
Console.WriteLine("Incorrect Input!");
}
}
while (!correctInput);
// this part is where is starts
do
{
Console.WriteLine("\nSet a month :");
correctInput = int.TryParse(Console.ReadLine(), out monthInput);
if (!correctInput || monthInput < 1 || monthInput > 12)
{
Console.WriteLine("Incorrect Input!");
}
}
while (!correctInput || monthInput < 1 || monthInput > 12);
do
{
Console.WriteLine("\nSet a date :");
correctInput = int.TryParse(Console.ReadLine(), out dateInput);
if (!correctInput || dateInput > 31 || dateInput < 1)
{
Console.WriteLine("Incorrect Input!");
}
else
{
if (dateInput > DateTime.DaysInMonth(yearInput, monthInput))
{
Console.WriteLine("The date doesn't reach that many!");
continue;
}
}
} while (!correctInput || dateInput > 31 || dateInput < 1);
DateTime day = getDayofDate(yearInput, monthInput, dateInput);
Console.WriteLine("\nIt is {0}.", day.DayOfWeek);
Console.ReadKey();
}
static public DateTime getDayofDate (int year, int month, int day)
{
return new DateTime(year, month, day);
}
}
I expect it to repeat the loop after it meets the error, but it shows ArgumentsOutOfRangeException instead.
The continue works, but still checks the loop's condition. However, the condition is false - the loop stops! To fix that, you can set correctInput to false, and also you can remove the continue - because there are no more statements after the if to execute (the computer automatically goes to the next iteration):
do
{
Console.WriteLine("\nSet a date :");
correctInput = int.TryParse(Console.ReadLine(), out dateInput);
if (!correctInput || dateInput > 31 || dateInput < 1)
{
Console.WriteLine("Incorrect Input!");
}
else
{
if (dateInput > DateTime.DaysInMonth(yearInput, monthInput))
{
Console.WriteLine("The date doesn't reach that many!");
correctInput = false; // Makes one more iteration of the loop
}
}
} while (!correctInput || dateInput > 31 || dateInput < 1);
I am currently doing a tree-house course in which you create a fitness console app that records your input exercise time , tallies it and gives you feedback depending on your and have received no help in the treehouse community , so if anyone could help me find a solution to the following it would be great help , im not sure if it has something to do with where the variable is placed , if it is in-between the braces in which in is called. Im not too sure im really new to this
using System;
namespace Treehouse.fitnessFrog
{
class Program
{
static void Main()
{
int runningTotal = 0;
bool keepGoing = true;
while(keepGoing) {
// Prompt user for minutes exercised
Console.Write("Enter how many minutes you exercised or type quit to exit ");
string entry = Console.ReadLine();
if(entry == "quit")
{
keepGoing = false;
}else{
try
{
int minutes = int.Parse(entry);
if(minutes <= 0)
{
Console.WriteLine("Not Acceptable");
continue;
}
else if(minutes <= 10)// Number 1
{
Console.WriteLine("Better than nothing, am I right ?");
}
else if(minutes <= 30) // Number 2
{
Console.WriteLine("You are still quite lazy");
}
else if(minutes <= 60) // Number 3
{
Console.WriteLine("Your doing all right i guess. But work on you're spelling!");
}
else
{
Console.WriteLine("Cool story bro");
}
}
catch(FormatException)
{
Console.WriteLine("That is not valid");
continue;
}
// Add minutes exercised to total
runningTotal = runningTotal + minutes;
// Display total minutes exercised to the screen
Console.WriteLine("You've entered "+ runningTotal + " minutes");
// Repeat until user quits
}
}
Console.WriteLine("Goodbye mate");
}
}
}
You should declare variable minutes outside try block:
int minutes = 0; // create variable here
try
{
minutes = int.Parse(entry); // here only use this variable
if(minutes <= 0)
{
// your code
}
//else if statements
...
}
if (testModetrue)
{
try
{
Console.Write("What number do you want the roll to be set to? (1-6)");
string diceString = Console.ReadLine();
int diceCheck = int.Parse(diceString);
if ((diceCheck >= minDiceValue) || (diceCheck <= maxDiceValue))
{
diceNo = int.Parse(diceString);
}
else if ((diceCheck <= minDiceValue) || (diceCheck >= maxDiceValue))
{
Console.WriteLine("Please enter a number between 1-6.");
break;
}
}
catch (Exception)
{
Console.WriteLine("An error has occured.");
return;
}
}
This code checks to see whether the answer given doesn't go past 6 or below 1, however whenever I run it, it does it anyway then it throws the out of array error, anybody help?
int diceCheck = int.Parse(diceString);
if ((diceCheck >= minDiceValue) || (diceCheck <= maxDiceValue))
{
diceNo = int.Parse(diceString);
}
This conditional should be AND rather than OR. Also, since you're parsing the string before the conditional, you don't need to do it inside it, so you should change that part to:
int diceCheck = int.Parse(diceString);
if (diceCheck > maxDiceValue && diceCheck < minDiceValue)
{
Console.Writeline("Please write a number between 1 and 6");
break;
}
Your other if statement was also kind of redundant because you already have other variable (dicecheck) with the value, so remove it.
private const int maxDiceValue = 6;
private const int minDiceValue = 1;
Console.Write("What number do you want the roll to be set to? (1-6)");
string diceString = Console.ReadLine();
int diceCheck;
if (!int.TryParse(diceString, out diceCheck) ||
diceCheck < minDiceValue ||
diceCheck > maxDiceValue) {
Console.WriteLine("Please enter a number between 1-6.");
return;
}
// add diceCheck to array here
Lets imagine the user introduce -1.
In the first condition you are validating if -1 >= 1 which is false, but you are also validating if -1 <= 6 which is true.
Instead of && (AND ALSO) you are using || (Or Else).
Since one of the condition is always true, the validating will always return true and therefore the code will run throwing an error.
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 >=
Below is my current code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int[] trialArray = new int[10];
public int trialCounter = -1;
private void button1_Click(object sender, EventArgs e)
{
bool button1Click = true;
if (button1Click == true)
{
ITIpanel.Visible = true;
for (int i = 0; i < trialArray.Length; i++) { trialArray[i] = -1; } // Set default value through array
int counter = 0;
Random rnd = new Random();
while (counter < 10 / 2)
{ // Red trials, fill half array
int index = rnd.Next(0, 10 - 1);
if (trialArray[index] == -1) { trialArray[index] = 1; ++counter; } //if unchanged value, change it
}
while (counter < 10)
{
int index = rnd.Next(0, 10);
if (trialArray[index] == -1) { trialArray[index] = 2; ++counter; }
}
}
}
private void ITIpanel_Paint(object sender, PaintEventArgs e)
{
if (ITIpanel.Visible == true)
{
trialCounter += 1;
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
ITIpanel.Visible = false;
timer1.Enabled = false;
if (trialArray[trialCounter] == 1) { redstimPanel.Visible = true; }
else { bluestimPanel.Visible = true;}
if (trialCounter == 9) { Application.Exit(); }
}
public int counter = 0;
public event EventHandler Clicked5TimesEvent;
private void OnClicked5TimesEvent()
{ if (Clicked5TimesEvent != null) { Clicked5TimesEvent(this, EventArgs.Empty); } }
private void bluestimPanel_MouseDown(object sender, EventArgs e)
{
//FR requirement
counter++; if (counter % 5 == 0) { redstimPanel.Visible = false; ITIpanel.Visible = true; }
}
private void redstimPanel_MouseDown(object sender, EventArgs e)
{
//FR requirement
counter++; if (counter % 5 == 0) { redstimPanel.Visible = false; ITIpanel.Visible = true; }
}
}
}
As you can see, I am attempting to make a global array with 10 items. On the button click the 10 items are supposed to be altered such that half contain the value 1 and the other half contain the value 2.
Then, on the timer tick, depending on the value in the trialCounter, which determines the part of the array to be accessed, it should display either the redstimPanel or the bluestimPanel.
Therefore, if the 'trialCounter' is equal to 8, and 8 in the TrialArray is equal 1, the 'redstimPanel' should become Visible. Alternatively, if 8 in the 'TrialArray' is equal to 2, the 'bluestimPanel' should become Visible.
This, however, is not working as I would like it to. Thus, there are clearly some issues with my code. Do you all have any suggestions?
You never reset counter, or have the second loop (the one setting the 2s) be the full array.
There is also an error with the random number, rnd.Next(a,b) a - lower bound (inclusive), b - upper bound (exclusive). So it should be rnd.Next(0,10); so you have a chance of populating the last array position.
while (counter < 10 / 2) { // Red trials, fill half array
int index = rnd.Next(0, 10);
if (trialArray[index] == -1) { trialArray[index] = 1; ++counter; } //if unchanged value, change it
}
//Counter on the first loop here is already 5 (it exited the previous loop)
//So allow it to get to 10, and populate the FULL array.
while (counter < 10) {
int index = rnd.Next(0, 10);
if (trialArray[index] == -1) { trialArray[index] = 2; ++counter; }
}
Allow me to give you some tips and some explanations regarding your code:
First of all, you probably wanted that local button1Click variable to know later on whether the button has been clicked or not. For that to work, you should place it outside that function, otherwise it's never going to be used, and will be true with every button click, something like this:
bool button1Click = false;
private void button1_Click(object sender, EventArgs e)
{
if (!button1Click)
{
When you have a condition, you want the code to decide, whether an expression is true or false you may omit the part "== true" because it doesn't add anything new.
You have two whiles. Your idea was to run the counter until 5, with the first piece of code, and then from 5 to 10 the second piece of code. Now let me try to explain what is actually going on. The counter will go on until 5 filling 1s at random indices. Then at 5, the expression in the while will become false and it breaks out from the loop. Since the second while has the very same expression, it simply avoids it and goes on. One of the many solutions would be to have an if in the loop like this:
while (counter < 10)
{
if (counter<5)
{
// fill red
}
else
{
// fill blue
}
}
The way you fill up the values in your array. Have you thought about what's going to happen when the same index will be generated several times? It means it'll overwrite the previous value while certain index will remain -1.