Logic to determine a postal carrier based on the tracking number C# - 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")

Related

Can I compare a value from a method and another from a variable?

I need to identify if password is equal to Pin(), I don't know if the problem is comparing a method inside a method
public static string Pin(int size = 4) {
StringBuilder sb = new StringBuilder(size);
while (sb.Length < size) {
var key = Console.ReadKey(true);
if (key.KeyChar >= '0' && key.KeyChar <= '9') {
sb.Append(key.KeyChar);
Console.WriteLine('*');
}
}
return sb.ToString();
}
static void Card() {
Console.WriteLine("Enter the 4 Digits Password");
int password = int.Parse(Console.ReadLine());
if (password == Pin()) {
// Is going to do something
}
}
You cannot compare string (Pin() result) and int (password) directly. Either convert password to string string password = Console.ReadLine();, either add int.Parse to the Pin() function result.
if (password == int.Parse(Pin()))
{
// Is going to do something
}
I suggest implementation like this. For reading Pin we can put
// Since Pin is integer, let's return int, not string
public static int Pin(int size = 4) {
if (size <= 0 || size >= 9)
throw new ArgumentOutOfRangeException(nameof(size));
StringBuilder sb = new StringBuilder(size);
while (sb.Length != size) {
var position = Console.GetCursorPosition();
char letter = Console.ReadKey().KeyChar;
Console.SetCursorPosition(position.Left, position.Top);
if (letter >= '0' && letter <= '9') {
Console.Write('*');
sb.Append(letter);
}
else {
Console.Write(' ');
Console.SetCursorPosition(position.Left, position.Top);
}
}
return int.Parse(sb.ToString());
}
Let's extract ReadInteger as well:
public static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Syntax error, incorrect integer value. Please, try again.");
}
}
Then you can use the routine as simple as
static void Card() {
int password = ReadInteger("Enter the 4 Digits Password");
if (password == Pin()){
// Is going to do something
}
}

Loop methodn not giving accurate resuts

I have created file during the runtime process John.txt and there are properties for John. The text of the file is "friend,banker" but when I execute and ask the AI "where is John"? it doesnt return any results despite I wrote the method MatchProffesionWithProperties. Where Am I wrong?
namespace Machine
{
class Program
{
static bool HavingGreeted = false;
static string person;
static Dictionary<string, string> KeyValuePairs;
static void MatchProffesionsWithProperties(string person,DayOfWeek dayOfWeek)
{
var strings = File.ReadAllLines(person + ".txt");
foreach(var stringi in strings)
{
var whitespacearray = stringi.Split(' ');
var commaarray = stringi.Split(',');
foreach(var property in whitespacearray)
{
if (KeyValuePairs.ContainsKey(property))
{
if (dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday || dayOfWeek == DayOfWeek.Wednesday || dayOfWeek == DayOfWeek.Thursday || dayOfWeek == DayOfWeek.Friday)
{
Console.WriteLine("{0} should be at the {1}", person, KeyValuePairs[property]);
}
}
}
foreach(var property in commaarray)
{
if (KeyValuePairs.ContainsKey(property))
{
if (dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday || dayOfWeek == DayOfWeek.Wednesday || dayOfWeek == DayOfWeek.Thursday || dayOfWeek == DayOfWeek.Friday)
{
Console.WriteLine("{0} should be at the {1}", person, KeyValuePairs[property]);
}
}
}
}
}
static void ProcessQuestionForPerson(string word)
{
var array = word.Split(' ');
if (word.Contains("Wh"))
{
person = array[2].Substring(0,array[2].Length-1);
}
else
{
person = array[1];
}
if (!File.Exists(person+".txt"))
{
Console.WriteLine("Who is {0}?", person);
string data = Console.ReadLine();
var filestream = File.Create(person + ".txt");
byte[] b = ASCIIEncoding.ASCII.GetBytes(data);
filestream.Write(b, 0, b.Length);
filestream.Close();
}
else
{
if (word.StartsWith("Who"))
{
string data = File.ReadAllText(person + ".txt");
Console.WriteLine("{0} is a {1}", person, data);
}
if (word.StartsWith("Where"))
{
MatchProffesionsWithProperties(person, DateTime.Today.DayOfWeek);
}
}
}
static void Greet(int hour)
{
if (hour > 0 && hour < 12)
{
Console.WriteLine("Good Morning");
}
if (hour > 12 && hour < 17)
{
Console.WriteLine("Good Afternoon");
}
if (hour > 17 && hour <= 23)
{
Console.WriteLine("Good Evening");
}
}
static void ProcessQuestionForMyself(string word)
{
var array = word.Split(' ');
//Process the components of the sentence
string type = array[1];
// get the type of the sentence
string value = array[3].Substring(0,array[3].Length-1);
// get the value of the sentence
string questiontype = array[3].Substring(0,array[3].Length-1);
//get the type of the question
if (word.EndsWith("."))
{
string correctvalue = File.ReadAllText(type+".txt");
// read from file the correct value
if (type == "name")
{
if (correctvalue == GetLowerUpper(value)[0] || correctvalue == GetLowerUpper(value)[1])
{
Console.WriteLine("Correct.My name is {0}.", value);
// print response
}
else
{
Console.WriteLine("{0} is not my name.", value);
// print response
}
}
if (type == "age")
{
if (correctvalue == value)
{
Console.WriteLine("Correct.I am {0} years old.", value);
// print response
}
else
{
Console.WriteLine("{0} is not my age.", value);
// print response
}
}
}
if (word.EndsWith("?"))
{
string answer = File.ReadAllText(questiontype+".txt");
Console.WriteLine(answer);
}
}
static string[] GetLowerUpper(string word)
{
string upperword = word.Replace(word[0].ToString(), word[0].ToString().ToUpper());
string lowerword = word.ToLower();
//Create strings for answer and question0
string[] array = new string[2] { upperword, lowerword };
return array;
}
static void MainThread()
{
if (HavingGreeted == false)
{
Greet(DateTime.Now.Hour);
HavingGreeted = true;
}
string data = Console.ReadLine();
if (data.Contains(GetLowerUpper("your")[0]) || data.Contains(GetLowerUpper("your")[1]))
{
//Append to me
ProcessQuestionForMyself(data);
}
if (!data.Contains("your"))
{
//Append to someone else
ProcessQuestionForPerson(data);
}
// Repeat thread
Thread repeatmainthread = new Thread(new ThreadStart(MainThread));
repeatmainthread.Start();
}
static void Main(string[] args)
{
KeyValuePairs = new Dictionary<string, string>();
KeyValuePairs.Add("Banker", "Bank");
Thread mainthread = new Thread(new ThreadStart(MainThread));
mainthread.Start();
}
}
}
The expected result would be the AI to tell me that John should be at the bank.
KeyValuePairs.ContainsKey(property) is case-sensitive, so "banker" will not match "Banker". You can allow case-insensitive searching by changing the initialisation of KeyValuePairs to:
KeyValuePairs = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
Changing ProcessQuestionForPerson to still ask a "Where is ..." question after creating a new file for that person:
static void ProcessQuestionForPerson(string word)
{
var array = word.Split(' ');
bool fileExisted = false;
if (word.Contains("Wh"))
{
person = array[2].Substring(0,array[2].Length-1);
}
else
{
person = array[1];
}
fileExisted = File.Exists(person+".txt");
if (!fileExisted)
{
Console.WriteLine("Who is {0}?", person);
string data = Console.ReadLine();
var filestream = File.Create(person + ".txt");
byte[] b = ASCIIEncoding.ASCII.GetBytes(data);
filestream.Write(b, 0, b.Length);
filestream.Close();
}
if (word.StartsWith("Who") && fileExisted) //We don't want to answer "Who" when we've just answered it ourselves (remove && fileExisted if you do)
{
string data = File.ReadAllText(person + ".txt");
Console.WriteLine("{0} is a {1}", person, data);
}
if (word.StartsWith("Where"))
{
MatchProffesionsWithProperties(person, DateTime.Today.DayOfWeek);
}
}

Getting a loop to build a string correctly

I'm trying to pull the tournament age from this webpage:
http://www.reddishvulcans.com/uk_tournament_database.asp
I'm trying to create a string based on the valid ages for entry for each table.
For example, if the "Carling Cup" is enterable by 7 year olds, then a string would be generated like "U7", or if it's enterable by 7, 8, and 9 year olds, the resulting string will be "U7, U8, U9".
I've made a start, however my logic will break if the ages go like this "Under 7s, Gap here where no under 8s, Under 9s".
Here is my code:
public static List<Record> getRecords()
{
string url = "http://www.reddishvulcans.com/uk_tournament_database.asp";
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
var root = doc.DocumentNode;
var ages = root.SelectNodes("//div[#class='infobox']/table/tr[5]/td/img");
List<String> tournamentAges = new List<String>();
String ageGroups = "";
List<String> ageString = new List<String>();
for (Int32 i = 0; i < ages.Count(); i++)
{
if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u6_Yes.gif")
{
if (!ageString.Contains(" U6 ")) {
ageString.Add(" U6 ");
continue;
}
}
else if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u6_.gif")
{
continue;
}
if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u7_Yes.gif")
{
if (!ageString.Contains(" U7 "))
{
ageString.Add(" U7 ");
continue;
}
}
else if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u7_.gif")
{
continue;
}
if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u8_Yes.gif")
{
if (!ageString.Contains(" U8 "))
{
ageString.Add(" U8 ");
continue;
}
}
else if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u8_.gif")
{
continue;
}
// Checks until u16.gif
foreach (String a in ageString)
{
if (a != "")
{
ageGroups += a;
}
}
ageString.Clear();
if (ageGroups != "")
{
tournamentAges.Add(ageGroups);
}
ageGroups = "";
}
}
}
To be clear, I'm having trouble with the loop logic.
The flow currently goes like this:
Loop through current list of images
If > u6_Yes.gif
Concatenate u6 to ageString
else
Continue
However it will continue back to the start and get stuck in an infinite loop, How can I make it gracefully handle when u6_.gif is gone, ignore it and go to the next?
why don't you just simplify your loop like this?
if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u6_Yes.gif")
{
if (!ageString.Contains(" U6 "))
{
ageString.Add(" U6 ");
continue;
}
}
if (ages[i].GetAttributeValue("src", "nope") == "images/2016/u7_Yes.gif")
{
if (!ageString.Contains(" U7 "))
{
ageString.Add(" U7 ");
continue;
}
}
}
(...)
just remove all those else if blocks...
Also, you should consider extraction src attribute from ages array. You can use Linq and make your loop a lot simplier. Something like this:
List<String> ageString = new List<String>();
List<string> imageSources = ages.Where(x => x.GetAttributeValue("src", "nope").StartsWith("images/2016/u") && x.GetAttributeValue("src", "nope").EndsWith("_Yes.gif")).ToList();
foreach (var src in imageSources)
{
ageString.Add(" " + src.Substring(11, 2).ToUpper() + " ");
}

C# for case in string(easy)

so I have this code. I need to generate a for loop that checks all the characters in the string and checks if they are all valid(So numbers from 0->7). But I don't know how to write it, I tried something but it didn't work. Here are the examples:user enters: 77, code works, user enters 99, code doesn't work, user enters 5., code doesn't work, etc..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NALOGA1
{
class Program
{
static string decToOct(int stevilo)//v mojon primere 7
{
string izhod = "";
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return izhod;
}
static int Octtodesetisko(string stevilo)
{
double vsota = 0;
for (int i = stevilo.Length - 1; i >= 0; i--)
{
int stevka = stevilo[i] - '0';
vsota += (stevka * Math.Pow(8, i));
}
return (int)vsota;
}
static void Main(string[] args)
{
//3 podprogram-in progress
string prvastevilka = Console.ReadLine();
int prvasprememba = Int32.Parse(prvastevilka);
if (prvasprememba > 0)
{
Console.WriteLine(decToOct(prvasprememba));
}
else
{
Console.WriteLine("Napaka");
}
string drugastevilka = Console.ReadLine();
int drugasprememba = Octtodesetisko(drugastevilka);
foreach (char znak in drugastevilka)
{
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
{
Console.WriteLine("Napaka");
}
else
{
Console.WriteLine("dela :D");
}
}
Console.ReadKey();
}
}
}
Personally, I would take advantage of the LINQ Enumerable.All method to express this in a very concise and readable way:
if (str.Any() && str.All(c => c >= '0' && c <= '7'))
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
EDIT: No LINQ
It's not hard to translate what the LINQ Enumerable.All method does to a normal loop. It's just more verbose:
bool isValid = true;
foreach (char c in str)
{
if (c < '0' || c > '7')
{
isValid = false;
break;
}
}
if (str.Length != 0 && isValid)
{
Console.WriteLine("good");
}
else
{
Console.WriteLine("bad");
}
Firstly, there seems to be a mistake in the line
if(znak!=1 || znak!=2 || znak!=3 || znak!=4 || znak!=5 || znak!=6 || znak!=7)
I guess it should read
if(znak!='1' || znak!='2' || znak!='3' || znak!='4' || znak!='5' || znak!='6' || znak!='7')
which should be compressed to
if (znak >= '0' && znak <= '7')
You can use linq instead of the for loop here like this:
if (drugastevilka.All(c => c >= '0' && c <= '7')
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
But the best solution is probably to use a regular expression:
Regex regex = new Regex("^[0-7]+$");
if (regex.IsMatch(drugastevilka))
Console.WriteLine("dela :D");
else
Console.WriteLine("Napaka");
Edit: the linq solution shown accepts empty strings, the regex (as shown) needs at least 1 character. Exchange the + with a * and it will accept empty strings, too. But I don't think you want to accept empty strings.
You are messing up with the datatype
Can you try with below code
static string decToOct(int stevilo)//v mojon primere 7
{
int izhod = 0;
//7>0 DRŽI
while (stevilo > 0)
{
//izhodi se dodeli ostanek deljenja z 8 keri se spremeni v string
izhod = (stevilo % 8) + izhod;
//7/8;
stevilo /= 8;
}
return (izhod.ToString());
}
What about something like this?
class Program
{
static void Main(string[] args)
{
string someString = "1234567";
string someOtherString = "1287631";
string anotherString = "123A6F2";
Console.WriteLine(IsValidString(someString));
Console.WriteLine(IsValidString(someOtherString));
Console.WriteLine(IsValidString(anotherString));
Console.ReadLine();
}
public static bool IsValidString(string str)
{
bool isValid = true;
char[] splitString = str.ToCharArray(); //get an array of each character
for (int i = 0; i < splitString.Length; i++)
{
try
{
double number = Char.GetNumericValue(splitString[i]); //try to convert the character to a double (GetNumericValue returns a double)
if (number < 0 || number > 7) //we get here if the character is an int, then we check for 0-7
{
isValid = false; //if the character is invalid, we're done.
break;
}
}
catch (Exception) //this will hit if we try to convert a non-integer character.
{
isValid = false;
break;
}
}
return isValid;
}
}
IsValidString() takes a string, converts it to a Char array, then checks each value as such:
Get the numeric value
Check if the value is between 0-7
GetNumericValue will fail on a non-integer character, so we wrap it in a try/catch - if we hit an exception we know that isValid = false, so we break.
If we get a valid number, and it's not between 0-7 we also know that isValid = false, so we break.
If we make it all the way through the list, the string is valid.
The sample given above returns:
IsValidString(someString) == true
IsValidString(someOtherString) == false
IsValidString(anotherString) == false

Math error using % in a loop

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);
}

Categories

Resources