Math error using % in a loop - c#

I am trying to use mod division to determine whether a year in a loop is a census or election year, and I have two issues:
1. I cannot get the wording in line with the year for ex:
It is like:
2000
this is an election year
this is a census year
2001
but I need it to say:
2000, this is an election year, this is a census year
2001 etc
2 : My math is some sort of wrong but I am having trouble identifying why or where, the division needs to apply to a user entered year range, and it needs to divide each year by 10, or 4, and the years that have no remainder are election or census years, but it is not doing that properly, it is not dividing all of the years, just some. My code is this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
startYr = int.Parse(textBoxStartYr.Text);
endYr = int.Parse(textBoxEndYr.Text);
if (int.TryParse(textBoxStartYr.Text, out startYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (int.TryParse(textBoxEndYr.Text, out endYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true )
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items.Add("This is a census year");
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items.Add("This is an election year");
}
else { }
}
else
{
//nothing
}
}
}

Try this:
private void buttonGo_Click(object sender, EventArgs e)
{
// Variables
int startYr = 0;
int endYr = 0;
bool checkForCensus = checkBoxCensus.Checked;
bool checkForElection = checkBoxElection.Checked;
// Input Validation
string errorMsg = "";
if (!int.TryParse(textBoxStartYr.Text, out startYr))
errorMsg += "Please enter a four digit year";
if (!int.TryParse(textBoxEndYr.Text, out endYr))\
errorMsg += String.Format("{0}Please enter a four digit year",
errorMsg == "" ? "" : " ");
if (errorMsg != "")
{
MessageBox.Show(errorMsg);
return;
}
// Loop
for (int yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isCensusYear, isElectionYear;
if (checkForCensus && (yearDisp % 10) == 0)
isCensusYear = true;
if (checkForElection && (yearDisp % 4) == 0)
isElectionYear = true;
listBoxDisp.Items.Add(String.Format("{0}: {1}{2}{3}",
yearDisp.ToString(),
isCensusYear ? "this is a census year" : "",
(isCensusYear && isElectionYear) ? "," : "",
isElectionYear ? "this is an election year" : ""
));
}
}
Notes:
The empty if and else statements are unnecessary. I have removed the to make them more concise.
On the topic of conditionals in if statements: the ! means "not" or "the opposite of". Examples: !false == true and !true == false.
You do not need the initial int.Parse() statements because TryParse()'s second parameter is an out parameter (it outputs the parsed integer).
I created two variables which get the value of the check box. That way you don't have to check the value every time the loop is executed.
I used a ternary operator and String.Format() to determine what text to display.
Although you didn't mention it, I did change the input validation so that only one message box is displayed.

Try this for your listbox issue.
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
int index = listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true)
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items[index] += ",This is a census year";
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items[index] += ",This is an election year";
}
else { }
}
else
{
//nothing
}
}

Try something like this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
if (!int.TryParse(textBoxStartYr.Text, out startYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (!int.TryParse(textBoxEndYr.Text, out endYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = 0 == (yearDisp % 4);
bool isCensus = 0 == (yearDisp % 10);
if (isCensus && checkBoxCensus.Checked && isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a both a census year and an election year", yearDisp));
}
else if (isCensus && checkBoxCensus.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a census year", yearDisp));
}
else if (isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is an election year", yearDisp));
}
else {
listBoxDisp.Items.Add(yearDisp.ToString());
}
}
}
Here's a more concise version of the for loop:
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = (0 == (yearDisp % 4)) && checkBoxCensus.Checked;
bool isCensus = 0 == (yearDisp % 10) && checkBoxElection.Checked;
string text = yearDisp.ToString();
if (isCensus && isElection)
{
text += " This is a both a census year and an election year";
}
else if (isCensus)
{
text += " This is a census year", yearDisp;
}
else if (isElection)
{
text += " This is an election year";
}
listBoxDisp.Items.Add(text);
}

Related

Logic to determine a postal carrier based on the tracking number C#

working on some simple logic to determine a postal carrier based on the tracking number. I am trying to put the tracking number into an array called "trackingNumberArray" then have a few if statements that compare various items of that array to determine the carrier. This is the code I have but still cannot seem to make it work. Any tips/guideance would be greatly appreciated!
static void Main(string[] args)
{
string trackingNumber = "1Z204E380338943508";
string[] trackingNumberArray = new string[] {trackingNumber};
if (trackingNumberArray.Contains("1Z"))
{
string carrierName = "UPS";
Console.WriteLine($"Carrier Name" + carrierName);
}
else if (trackingNumberArray.Length >= 12 && trackingNumberArray.Length < 14 && !!trackingNumberArray.Contains("1Z"))
{
string carrierName = "Fedex";
Console.WriteLine($"Carrier Name" + carrierName);
}
else if (trackingNumberArray.Length >= 20 && trackingNumberArray.Length < 22 && !trackingNumberArray.Contains("1Z"))
{
string carrierName = "USPS";
Console.WriteLine($"Carrier Name" + carrierName);
}
else
{
string carrierName = null;
Console.WriteLine($"did not work" + carrierName);
}
}
Instead of putting the tracking number into an array, you can just leave it as a string. The rest of your code should then work with that string. You also don't need the redundant checks for "1Z", since that was in the first conditon:
static void Main()
{
string trackingNumber = "1Z204E380338943508";
string carrierName = null;
if (trackingNumber.Contains("1Z"))
{
carrierName = "UPS";
}
else if (trackingNumber.Length >= 12 && trackingNumber.Length < 14)
{
carrierName = "FedEx";
}
else if (trackingNumber.Length >= 20 && trackingNumber.Length < 22)
{
carrierName = "USPS";
}
if (carrierName == null)
{
Console.WriteLine("Did not work.");
}
else
{
Console.WriteLine($"Carrier name: {carrierName}");
}
GetKeyFromUser("\nPress any key to exit...");
}
You could then create a static method out of the code:
public static string GetCarrierName(string trackingNumber)
{
if (trackingNumber == null) return null;
if (trackingNumber.Contains("1Z")) return "UPS";
if (trackingNumber.Length >= 12 && trackingNumber.Length < 14) return "FedEx";
if (trackingNumber.Length >= 20 && trackingNumber.Length < 22) return "USPS";
return null;
}
And use it like:
static void Main()
{
string carrierName = GetCarrierName("1Z204E380338943508");
if (carrierName == null)
{
Console.WriteLine("Unknown tracking id format.");
}
else
{
Console.WriteLine($"Carrier name: {carrierName}");
}
GetKeyFromUser("\nPress any key to exit...");
}
trackingNumberArray.Contains("1Z")
This won't work because your array is made up of individual letters. If you want to look for a string, use the original string.
trackingNumber.Contains("1Z")
Also, there's no need for this bit, because it's in an 'else' that can only be reached when it's true.
&& !trackingNumberArray.Contains("1Z")

Library for calculating GTIN from EAN-13 barcode

I am creating an XML from a backend that is supposed to be fed into a GDSN datapool. The company has a very old backend which only has their own PLU number and barcode attached to every item. What I know is that (at least here in Iceland) most GTIN are the EAN-13 barcode with a padded 0 at the front although this is not always the case. Do you know of a library that could check if a GTIN is correct i.e. would calculate the check digit?
I am using a windows form and am using C#.
First to validate what you want to do:
https://www.gs1.org/services/check-digit-calculator
Then you have 2 possibilities for GTIN since it must be 14 digits long.
The case you described, then you pad a 0 on the left
A GTIN with right length is provided directly (which is possible and left digit will not be 0)
Here is a quick example on how you can check this, based on the fact you know the gtin string only contains digits:
public Boolean ValidateGTIN(string gtin)
{
string tmpGTIN = gtin;
if (tmpGTIN.Length < 13)
{
Console.Write("GTIN code is invalid (should be at least 13 digits long)");
return false;
}
else if (tmpGTIN.Length == 13)
{
tmpGTIN = "0" + gtin;
}
// Now that you have a GTIN with 14 digits, you can check the checksum
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(tmpGTIN[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(tmpGTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
Thanks for that. This is almost there. I would like to take it a step further - I am going to copy your code and add a little:
//First create a function only for validating
//This is your code to almost all - variable names change
public Boolean validateGTIN(string gtin)
{
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(gtin[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(GTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
//Here we change quite a bit to accommodate for edge cases:
//We return a string which is the GTIN fully formed or we throw and exception.
public String createGTIN(string bcFromBackend)
{
string barcodeStr = bcFromBackend;
//Here we check if the barcode supplied has fewer than 13 digits
if (barcodeStr.Length < 13)
{
throw new System.ArgumentException("Barcode not an EAN-13
barcode");
}
//If the barcode is of length 13 we start feeding the value with a padded 0
//into our validate fuction if it returns false then we pad with 1 and so on
//until we get to 9. It then throws an error if not valid
else if (barcodeStr.Length == 13)
{
if(validateGTIN("0"+ barcodeStr))
{
return "0" + barcodeStr;
}
else if(validateGTIN("1" + barcodeStr))
{
return "1" + barcodeStr;
}
else if(validateGTIN("2" + barcodeStr))
{
return "2" + barcodeStr;
}
else if(validateGTIN("3" + barcodeStr))
{
return "3" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("5" + barcodeStr))
{
return "5" + barcodeStr;
}
else if(validateGTIN("6" + barcodeStr))
{
return "6" + barcodeStr;
}
else if(validateGTIN("7" + barcodeStr))
{
return "7" + barcodeStr;
}
else if(validateGTIN("8" + barcodeStr))
{
return "8" + barcodeStr;
}
else if(validateGTIN("9" + barcodeStr))
{
return "9" + barcodeStr;
} else {
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode")
}
}
//Lastly if the barcode is of length 14 we try with this value. Else throw
//error
else if(barcodeStr.Length == 14)
{
if(validateGTIN(barcodeStr)
{
return barcodeStr;
}
else
{
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode");
}
}
Hopefully this makes sense. I have not sent the code through testing as I don't have my IDE on my current computer installed. Is

Computation of final grades in a listview

This is all of the code i have done so far. The system has a listview that has a column header:
subject name | 1st | 2nd | 3rd | 4th | Final Grades
If the column 1st to 4th contains value it will compute for the final grade of the student. sum(1st to 4th) / 4 *50 + 50. if one of the column does not have a value then the user will be prompted and no final grades will be computed.
I am confused on how do i get all the listview value from 1st to 4th then automatically computes the final grade.
PLease help
private void button1_Click(object sender, EventArgs e)
{
flag = false;
if (txt_numValue.Text != "")
{
char[] entereddata = txt_numValue.Text.ToCharArray();
foreach (char aChar in entereddata.AsEnumerable())
{
if (!Char.IsDigit(aChar))
{
MessageBox.Show("Please enter only numbers.", "In the field Numeric Value");
flag = true;
break;
}
}
}
else if (txt_numValue.Text == "")
{
MessageBox.Show("Please do not leave the field, 'Numeric Value', blank.", "Attention!");
flag = true;
}
if (flag == false)
{
string period = txt_gradingPeriod.Text;
string numeric = txt_numValue.Text;
int cell = 0;
if (period == "1st") { cell = 1; }
else if (period == "2nd") { cell = 2; }
else if (period == "3rd") { cell = 3; }
else if (period == "4th") { cell = 4; }
foreach (ColumnHeader header in listView1.Columns)
{
if (header.Text == period)
{
listView1.Items[0].SubItems[cell].Text = numeric;
break;
}
}
}
}
Once you have got all the data in your list view you can do something like this,
int sum = 0;
foreach (ListViewItem v in listView1.Items)
{
bool hasBlank = false;
for (int i = 0; i < v.SubItems.Count;i++ )
{
if (v.SubItems[i].Text == null || v.SubItems[i].Text == string.Empty)
{
//code
hasBlank = true;
break;
}
else
{
sum += Convert.ToInt16(v.SubItems[i].Text);
}
}
if (!hasBlank)
{
string grade="something";
//formula to calculate grade based on sum.set the result to string grade
v.SubItems[4].Text = grade;
}
else
{
v.SubItems[4].Text = "has blank";
}
sum = 0;
}
This will fill grade if all values are present else a message that it has a blank value.

how to remove space after pressing buttons

i was doing a ITP assignment, when i got an error. The code for the part with the problem is:
private void btnAddWord_Click(object sender, EventArgs e)
{
//if the textbox is empty
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
}
//if the number of items in the listbox is greater than 29
else if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
}
//error message for entering word that is already in the list
bool contains = false;
for (int i = 0; i < lbxUnsortedList.Items.Count; i++)
{
if (lbxUnsortedList.Items[i].ToString().ToLower() == this.tbxAddWord.Text.ToString().ToLower())
{
contains = true;
}
}
//if there is no match in the list
if (!contains)
{
//add word to the listbox
lbxUnsortedList.Items.Add(tbxAddWord.Text);
//update tbxListBoxCount
tbxListboxCount.Text = lbxUnsortedList.Items.Count.ToString();
//onclick, conduct the bubble sort
bool swapped;
string temp;
do
{
swapped = false;
for (int i = 0; i < lbxUnsortedList.Items.Count - 1; i++)
{
int result = CarNameData[i].ToString().CompareTo(CarNameData[i + 1]);
if (result > 0)
{
temp = CarNameData[i];
CarNameData[i] = CarNameData[i + 1];
CarNameData[i + 1] = temp;
swapped = true;
}
}
} while (swapped == true);
tbxAddWord.Text = "";
}
// if there is a match in the list
else
{
MessageBox.Show("The word that you have added is already on the list");
tbxAddWord.Text = "";
tbxAddWord.Focus();
}
}
When i leave the textbox blank and click the add button, it comes up with the error message, but still adds a blank space. how do i stop this from happening?
You need to return from the method if you don't want to execute more code:
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
return;
}
//if the number of items in the listbox is greater than 29
else if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
return;
}
First thing is if you are using CarNameData list as Generic collection list List<string> its allows inbuilt sort method like CarNameData.Sort();
Second thing you have to put your code in else part like this
private void btnAddWord_Click(object sender, EventArgs e)
{
//if the textbox is empty
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
}
else
{
//if the number of items in the listbox is greater than 29
if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
}
//error message for entering word that is already in the list
bool contains = false;
for (int i = 0; i < lbxUnsortedList.Items.Count; i++)
{
if (lbxUnsortedList.Items[i].ToString().ToLower() == this.tbxAddWord.Text.ToString().ToLower())
{
contains = true;
}
}
//if there is no match in the list
if (!contains)
{
//add word to the listbox
lbxUnsortedList.Items.Add(tbxAddWord.Text);
//update tbxListBoxCount
tbxListboxCount.Text = lbxUnsortedList.Items.Count.ToString();
//onclick, conduct the bubble sort
bool swapped;
string temp;
do
{
swapped = false;
for (int i = 0; i < lbxUnsortedList.Items.Count - 1; i++)
{
int result = CarNameData[i].ToString().CompareTo(CarNameData[i + 1]);
if (result > 0)
{
temp = CarNameData[i];
CarNameData[i] = CarNameData[i + 1];
CarNameData[i + 1] = temp;
swapped = true;
}
}
} while (swapped == true);
tbxAddWord.Text = "";
}
// if there is a match in the list
else
{
MessageBox.Show("The word that you have added is already on the list");
tbxAddWord.Text = "";
tbxAddWord.Focus();
}
}
}

Multiple if conditions check in single button click

My C# code is something like as follows.
if(TextBox1.Text.Length > 5)
{
if(TextBox2.Text.Length > 5)
{
if(TextBox3.Text.Length > 5)
{
if(TextBox4.Text.Length > 5)
{
//Action to pass to the next stage.
}
else
{
error4.text = "Textbox4 value should be minimum of 5 characters.";
}
}
else
{
error3.text = "Textbox3 value should be minimum of 5 characters.";
}
}
else
{
error2.text = "Textbox2 value should be minimum of 5 characters.";
}
}
else
{
error1.text = "Textbox1 value should be minimum of 5 characters.";
}
1) In the above kind of sample. I am using nested If-Else concept where on button click, if TextBox1 value is less than 5 is moves to else part and shows the error1 value but it will not check for further errors.
2) If I change If conditions to step by step If conditions then it will not work for me because the action must be done only if all the IF conditions satisfies.
3) If I use && operator to check all conditions I will not get individual error to each "error label"
How can I check multiple IF conditions on a single button click?
My original code
if (checkavail == "available")
{
if (name.Text.Length > 0)
{
if (email.Text.Length > 5)
{
if (password1.Text.Length > 7 && password1.Text == password2.Text)
{
if (alternate.Text.Contains("#") && alternate.Text.Contains("."))
{
if (question.Text.Length > 0)
{
if (answer.Text.Length > 0)
{
Response.Redirect("next_page.aspx");
}
else
{
error5.Text = "Please enter your security answer";
}
}
else
{
error4.Text = "Please enter your security question";
}
}
else
{
error3.Text = "Invaild alternate email address";
}
}
else
{
error2.Text = "Password should be minimum 8 characters and must match confirm password";
}
}
else
{
error1.Text = "Email address should be minimum 6 characters";
}
}
else
{
error.Text = "Please enter your name";
}
}
else
{
error1.Text = "This email address is already taken. Please try another";
}
I need the Redirect action to be done upon satisfying all conditions. If more than one error was found each error should get each error message.
Make a function that just handles the error messages. Return an Enumerable from this function. Then you can format your if-statements like this and it will return an Enumerable:
private IEnumerable GetErrors()
{
if (TextBox1.Text.Length > 5) { yield return "Textbox1 minimum bla bla"; }
if (TextBox2.Text.Length > 5) { yield return "Textbox2 minimum bla bla"; }
if (TextBox3.Text.Length > 5) { yield return "Textbox3 minimum bla bla"; }
}
Make another function that handles your non-error message logic and just perform an if-statement to see if there were zero errors or not:
public void DoSomething()
{
var errors = GetErrors();
if (errors.Count == 0)
Response.Redirect("next_page.aspx");
else
error.Text = "Please fix your errors";
}
Thanks to all. I found my answer in below manner
string p1, p2, p3, p4;
if (TextBox1.Text.Length > 5)
{
p1 = "pass";
Label1.Text = "";
}
else
{
Label1.Text = "Textbox1 value should be minimum 5 characters.";
p1 = "fail";
}
if (TextBox2.Text.Length > 5)
{
p2 = "pass";
Label2.Text = "";
}
else
{
Label2.Text = "Textbox2 value should be minimum 5 characters.";
p2 = "fail";
}
if (TextBox3.Text.Length > 5)
{
p3 = "pass";
Label3.Text = "";
}
else
{
Label3.Text = "Textbox3 value should be minimum 5 characters.";
p3 = "fail";
}
if (TextBox4.Text.Length > 5)
{
p4 = "pass";
Label4.Text = "";
}
else
{
Label4.Text = "Textbox4 value should be minimum 5 characters.";
p4 = "fail";
}
if (p1 == "pass" && p2 == "pass" && p3 == "pass" && p4 == "pass")
{
Status.Text = "All pass";
}

Categories

Resources