C# Grade Calculator - c#

I'm currently coding a grades calculator that adds 3 test scores and gives you a letter grade depending on the average. So far I have been able to code everything without any issues except for one thing. In this calculator I added a checkbox that drops the lowest grade and averages out the highest 2 if checked. I just started programming a few weeks ago and have no idea how begin coding this. Should I use an if statement or a loop? If you guys have any tips on eliminating unnecessary code or anything else, feel free to point it out.
public frmGradeCalculator()
{
InitializeComponent();
}
private void chkDropLowest_CheckedChanged(object sender, EventArgs e)
{
}
private void btnClear_Click(object sender, EventArgs e)
{
// Clear Text
txtTest1.Clear();
txtTest2.Clear();
txtTest3.Clear();
txtAverage.Clear();
txtLetterGrade.Clear();
// Set Focus
txtTest1.Focus();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
// Declare variables
byte bytTest1;
byte bytTest2;
byte bytTest3;
float fltAverage;
string strLetterGrade = "F";
// Convert to text
if (byte.TryParse(txtTest1.Text, out bytTest1))
{
}
else
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtTest1.Focus();
return;
}
if (byte.TryParse(txtTest2.Text, out bytTest2))
{
}
else
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtTest2.Focus();
return;
}
if (byte.TryParse(txtTest3.Text, out bytTest3))
{
}
else
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtTest3.Focus();
return;
}
// Formula
fltAverage = (bytTest1 + bytTest2 + bytTest3) / 3;
if (fltAverage <= 59.9)
{
strLetterGrade = "F";
}
else if (fltAverage <= 63.9)
{
strLetterGrade = "D-";
}
else if (fltAverage <= 66.9)
{
strLetterGrade = "D";
}
else if (fltAverage <= 69.9)
{
strLetterGrade = "D+";
}
else if (fltAverage <= 73.9)
{
strLetterGrade = "C-";
}
else if (fltAverage <= 76.9)
{
strLetterGrade = "C";
}
else if (fltAverage <= 79.9)
{
strLetterGrade = "C+";
}
else if (fltAverage <= 83.9)
{
strLetterGrade = "B-";
}
else if (fltAverage <= 86.9)
{
strLetterGrade = "B";
}
else if (fltAverage <= 89.9)
{
strLetterGrade = "B+";
}
else if (fltAverage <= 93.9)
{
strLetterGrade = "A-";
}
else if (fltAverage <= 96.9)
{
strLetterGrade = "A";
}
else
{
strLetterGrade = "A+";
}
// convert back to user
txtAverage.Text = fltAverage.ToString("f1");
txtLetterGrade.Text = strLetterGrade.ToString();
}
private void btnExit_Click(object sender, EventArgs e)
{
// Exit application
Application.Exit();
}
private void frmGradeCalculator_Load(object sender, EventArgs e)
{
}
}
}

To answer your specific question on whether to use a loop or an if statement, all checkbox controls have a Checked property that you can check.
if(chkDropLowest.Checked)
{
//Calculate average without the lowest test
}
As far as design goes, I would recommend that you not assign so much functionality to a specific button. I would instead create a new method to call from that button (that way you are safe if you ever decide to use a new control in the future)
Example:
private string CalculateLetterGrade(byte test1, byte test2, byte test3)
{
string letterGrade;
if(chkDropLowest.Checked)
{
//Drop lowest test then calculate average
}
else
{
//Use all tests then calculate average
}
//Determine the string for the letter grade, then return it
return letterGrade;
}
You seem to have the average logic worked out so I'll leave that to you.

Give this a shot when you go to calculate the average:
double totalScore = bytTest1 + bytTest2 + bytTest3;
double lowest = Math.Min(Math.Min(bytTest1, bytTest2), bytTest3);
if (chkDropLowest.IsChecked == true)
{
// Drop the lowest test
fltAverage = (totalScore - lowest) / 2;
}
else
{
// Include all three tests
fltAverage = (totalScore) / 3;
}

Just a little bit for interest sake I've refactored your btnCalculate_Click. This solves your problem, but I've posted it more so that you can have a look at code that more tersely solves your problem and maybe give you some syntax to look at.
private void btnCalculate_Click(object sender, EventArgs e)
{
Func<TextBox, double?> parseTextBox = tb =>
{
double value;
if (!double.TryParse(tb.Text, out value))
{
MessageBox.Show("Invalid Number!",
"Yancarlos Grade Calculator",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
tb.Focus();
return null;
}
return value;
};
double?[] tests =
(
from tb in new[] { txtTest3, txtTest2, txtTest1, }
let result = parseTextBox(tb)
orderby result descending
select result
).ToArray();
if (tests.Any(t => t == null))
{
return;
}
double average =
tests
.Take(3 - (checkBox1.Checked ? 1 : 0))
.Average()
.Value;
var grades = new[]
{
new { Score = 59.9, Grade = "F" },
new { Score = 63.9, Grade = "D-" },
new { Score = 66.9, Grade = "D" },
new { Score = 69.9, Grade = "D+" },
new { Score = 73.9, Grade = "C-" },
new { Score = 76.9, Grade = "C" },
new { Score = 79.9, Grade = "C+" },
new { Score = 83.9, Grade = "B-" },
new { Score = 86.9, Grade = "B" },
new { Score = 89.9, Grade = "B+" },
new { Score = 93.9, Grade = "A-" },
new { Score = 96.9, Grade = "A" },
new { Score = 100.0, Grade = "A+" },
};
string grade =
grades
.Where(g => g.Score >= average)
.Select(g => g.Grade)
.First();
txtAverage.Text = average.ToString("f1");
txtLetterGrade.Text = grade;
}

Related

Binary Search an array to display a row of strings in a listview c# (Visual Studio)

This image shows what happens after type the name smith and press button searchI have a CSV text file full of data that is loaded in to an array and displayed in a listview. It has multiple columns and rows. The Columns are ext code, forename, surname. Each row is a different record. I have created a text box that will allow the user to input the surname of a record. Then a search button will allow the user to search on surname for extension number. Ideally the program should cope with multiple employees with the same surname, and match on just the first part of the surname; e.g. Sm for Smith and Smyth. It is a basic requirement that searching is not case sensitive.
A binary Search has to be used.
There are two methods that i tried, however i don't fully understand.
The button should only call the function.
Below is what I have tried, however it is not correct. Help will be greatly appreciated.
private void searchName()
{
Array.Sort(partsTable, (x, y) => string.Compare(x.surname, y.surname));
Clear();
int nameIndex = binarySearch(partsTable, txtSurname.Text);
ListViewItem phone = new ListViewItem();
phone.Text = (Convert.ToString(partsTable[nameIndex].surname));
phone.SubItems.Add(Convert.ToString(partsTable[nameIndex].forename));
phone.SubItems.Add(Convert.ToString(partsTable[nameIndex].extensionCode));
lstOutput.Items.Add(phone);
}
private int binarySearch(phone[] partsTable, string Key)
{
/* int left = 0;
int right = partsTable.Length - 1;
int nameIndex = -1;
bool found = false;
while (found != true && left <= right)
{
int mid = (left + right) / 2;
if (string.Compare(partsTable[mid].surname, Key, true) == 0)
{
found = true;
nameIndex = mid;
MessageBox.Show("If 1");
}
else if (string.Compare(partsTable[mid].surname, Key, true) > 0)
{
right = mid;
MessageBox.Show("If 2");
}
else
{
left = mid;
MessageBox.Show("If 3");
}
}
return nameIndex;
*/
/* while (left <= right)
{
if (left > right)
{
MessageBox.Show("Search Failed");
}
else
{
int mid = (left + right) / 2;
if (Key == partsTable[mid].surname)
return mid;
else if (String.Compare(Key, partsTable[mid].surname) < 0)
right = mid - 1;
else
left = mid + 1;
}
}
return -2;
*/
}
private void btnSearch_Click(object sender, EventArgs e)
{
string Key = txtSurname.Text;
int answer = binarySearch(partsTable, Key);
textBox1.Text = Convert.ToString(answer);
if (answer >= -1)
{
string message = "Extension code already in use";
string title = "Error";
MessageBox.Show(message, title);
extensionCode.Text = string.Empty;
forename.Text = string.Empty;
surname.Text = string.Empty;
lstOutput.Items.Clear();
}
}
Here is a simple demo that uses a list to store temp variable(table data). And then use "do ... while" to traverse the list.
private void btSearch_Click(object sender, EventArgs e)
{
lstOutput.Items.Clear();
do
{
searchName();
if (index != -1)
{
people.RemoveAt(index);
}
}
while (!isnull);
}
List<Person> people = new List<Person> {
new Person { No = 1, Surname = "Smith"} ,
new Person { No = 2, Surname = "Smit"},
new Person { No = 3, Surname = "Bob"},
new Person { No = 4, Surname = "KKK"},
new Person { No = 5, Surname = "Obt"},
new Person { No = 6, Surname = "Peter"}};
private void Form1_Load(object sender, EventArgs e)
{
lstOutput.View = View.Details;
people.Sort((x, y) => { return x.Surname.CompareTo(y.Surname); });
}
bool isnull = false;
int index;
private void searchName()
{
index = BinarySearch(people, 0, people.Count, txtSurname.Text);
if (index != -1)
{
ListViewItem phone = new ListViewItem();
phone.Text = (Convert.ToString(people[index].No));
phone.SubItems.Add(Convert.ToString(people[index].Surname));
lstOutput.Items.Add(phone);
}
else
{
isnull = true;
}
}
List<int> list = new List<int>();
private int BinarySearch(List<Person> p, int low, int high, string key)
{
int mid = (low + high) / 2;
if (low > high)
return -1;
else
{
try
{
string str = p[mid].Surname.Substring(0, key.Length);
if (string.Compare(str, key) == 0)
return mid;
else if (string.Compare(str, key) > 0)
return BinarySearch(p, low, mid - 1, key);
else
return BinarySearch(p, mid + 1, high, key);
}
catch
{
return -1;
}
}
}
class Person
{
public int No { get; set; }
public string Surname { get; set; }
}

C# Voice Recognition code not working on some machines

I have made a voice recognition program in C#. It was all working fine and then randomly stopped working. Now it doesn't respond to any input or say the first output s.Speak("hello, how may i assist you?"); when it's started like it's supposed to.
I have ran the program on my friend's Windows 10 system and it runs fine. This leads me to believe that it's a problem with my system. I am using Windows 7 by the way.
Heres the code -
using System;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
using System.Diagnostics;
using System.Xml;
using System.Media;
namespace JarvisTest
{
public partial class Form1 : Form
{
SpeechSynthesizer s = new SpeechSynthesizer();
Boolean wake = false;
String name = "Rhys";
String temp;
String condition;
String high;
String low;
Choices list = new Choices();
public Form1()
{
SpeechRecognitionEngine rec = new SpeechRecognitionEngine();
list.Add(new String[] { "hello", "bye", "how are you", "great", "what time is it", "whats the date", "open google", "open youtube", "wake", "sleep", "restart", "update", "whats the weather", "whats the temperature", "jarvis", "shut down", "exit", "play", "pause", "spotify", "last track", "next track", "whats todays high", "whats todays low", "whats todays weather", "whats your favorite song", "never mind", "whats my name", "minimise", "maximise"});
Grammar gr = new Grammar(new GrammarBuilder(list));
try
{
rec.RequestRecognizerUpdate();
rec.LoadGrammar(gr);
rec.SpeechRecognized += rec_SpeachRecognized;
rec.SetInputToDefaultAudioDevice();
rec.RecognizeAsync(RecognizeMode.Multiple);
}
catch { return; }
s.SelectVoiceByHints(VoiceGender.Male);
s.Speak("hello, how may i assist you?");
InitializeComponent();
}
public String GetWeather(String input)
{
String query = String.Format("https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=' Guernsey')&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
XmlDocument wData = new XmlDocument();
try
{
wData.Load(query);
}
catch
{
//MessageBox.Show("No internet connection");
return "No internet connection detected";
}
XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
XmlNode channel = wData.SelectSingleNode("query").SelectSingleNode("results").SelectSingleNode("channel");
XmlNodeList nodes = wData.SelectNodes("query/results/channel");
try
{
int rawtemp = int.Parse(channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value);
int rawhigh = int.Parse(channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["high"].Value);
int rawlow = int.Parse(channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["low"].Value);
temp = (rawtemp - 32) * 5/9 + "";
high = (rawhigh - 32) * 5 / 9 + "";
low = (rawlow - 32) * 5 / 9 + "";
condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["text"].Value;
if (input == "temp")
{
return temp;
}
if (input == "high")
{
return high;
}
if (input == "low")
{
return low;
}
if (input == "cond")
{
return condition;
}
}
catch
{
return "Error Reciving data";
}
return "error";
}
public void restart()
{
Process.Start(#"C:\Users\Rhys-Le-P\Documents\Visual Studio 2017\Projects\JarvisTest\JarvisTest\obj\Debug\JarvisTest.exe");
Environment.Exit(1);
}
public void shutdown()
{
Environment.Exit(1);
}
public void say(String h)
{
s.Speak(h);
wake = false;
}
String[] greetings = new String[3] { "hi", "hello", "hi, how are you" };
public String greetings_action()
{
Random r = new Random();
return greetings[r.Next(3)];
}
//Commands
private void rec_SpeachRecognized(object sender, SpeechRecognizedEventArgs e)
{
String r = e.Result.Text;
if (r == "jarvis")
{
wake = true;
//say(greetings_action());
SoundPlayer simpleSound = new SoundPlayer(#"C:\Users\Rhys-Le-P\Downloads\Beep.wav");
simpleSound.Play();
}
// if (r == "wake")
// {
// wake = true;
// say("i am awake");
// }
//if (r == "sleep")
//{
// wake = false;
// say("zzz");
// }
if (wake == true)
{
if (r == "minimise")
{
this.WindowState = FormWindowState.Minimized;
}
if (r == "maximise")
{
this.WindowState = FormWindowState.Maximized;
}
if (r == "whats my name")
{
say("your name is " + name);
}
if (r == "next track")
{
SendKeys.Send("^{RIGHT}");
//say("playing next track");
}
if(r == "last track")
{
SendKeys.Send("^{LEFT}");
//say("playing last track");
}
if(r == "spotify")
{
Process.Start(#"C:\Users\Rhys-Le-P\AppData\Roaming\Spotify\Spotify.exe");
}
//{
// input
if (r == "play" || r == "pause")
{
SendKeys.Send(" ");
}
// input
if (r == "hello")
{
//output
say("hi");
}
// input
if (r == "how are you")
{
//output
say("good, and you?");
}
// input
if (r == "bye")
{
//output
say("good bye!");
}
// input
if (r == "great")
{
//output
say("good to hear!");
}
// input
if (r == "what time is it")
{
//output
say(DateTime.Now.ToString("h:mm tt"));
}
// input
if (r == "whats the date")
{
//output
say(DateTime.Now.ToString("d/M/yyyy"));
}
// input
if (r == "open google")
{
//output
say("opening google");
Process.Start("http://www.google.com");
}
// input
if (r == "open youtube")
{
//output
say("opening youtube");
Process.Start("http://www.youtube.com");
}
// input
if (r == "restart" || r == "update")
{
//output
say("restarting");
restart();
}
if (r == "whats todays weather")
{
say("Todays weather is, " + GetWeather("cond") + "with a high of" + GetWeather("high") + "degrees and a low of" + GetWeather("low") +"degrees");
}
if (r == "whats the weather")
{
say("The sky is, " + GetWeather("cond") + ".");
}
if (r == "whats the temperature")
{
say("it is, " + GetWeather("temp") + "degrees.");
}
if (r == "whats todays high")
{
say("Todays high is, " + GetWeather("high") + "degrees.");
}
if (r == "whats todays low")
{
say("Todays low is, " + GetWeather("low") + "degrees.");
}
// input
if (r == "shut down" || r == "exit")
{
//output
say("Shutting Down System");
shutdown();
}
if (r == "whats your favorite song")
{
say("I love this song!");
SoundPlayer simpleSound = new SoundPlayer(#"C:\Users\Rhys- Le-P\Downloads\BSIM.wav");
simpleSound.Play();
}
if (r == "never mind")
{
say("Ok sir");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Any help is greatly appreciated! :)

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.

Clearing an array

I'm having a problem on an assignment, I can't clear the array. Also in my MessageBox when it displays the scores I get a zero as the first number no matter what I do. I can't figure out what to change so zero is not the first element.
public partial class Form1 : Form
{
int scoreTotal = 0;
int scoreCount = 0;
decimal average = 0;
int[] scoreTotalArray = new int[1];
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
Int32 score = Convert.ToInt32(txtScore.Text);
scoreTotalArray[scoreCount] = score;
Array.Resize(ref scoreTotalArray, scoreTotalArray.Length + 1);
scoreTotal += score; //accumulator
scoreCount++; //counter
average = scoreTotal / (decimal)scoreCount;//average
txtScoreCount.Text = scoreCount.ToString();//display in score count txtbox
txtScoreTotal.Text = scoreTotal.ToString(); //display in score total txtbox
txtAverage.Text = average.ToString("n2"); //display in average text box
txtScore.Clear();
txtScore.Focus();
}
}
catch (Exception ex) //catches all other exceptions
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
public bool IsValidData()
{
return
IsPresent(txtScore, "Score:") &&
IsInt32(txtScore, "Score:") &&
IsWithinRange(txtScore, "Score:", 0, 100);
}
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field, please enter a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
public bool IsInt32(TextBox textBox, string name)
{
try
{
Convert.ToInt32(textBox.Text);
return true;
}
catch (FormatException)
{
MessageBox.Show(name + "must be a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
}
public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + " must be between " + min + " and " + max + ".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
private void btnDisplayScore_Click(object sender, EventArgs e)
{
Array.Sort(scoreTotalArray);
string scoreCountString = "\n";
for(int i = 0; i < scoreCount; i++)
scoreCountString += scoreTotalArray [i] + "\n";
MessageBox.Show(scoreCountString + "\n", "Sorted Scores");
}
private void btnClearScores_Click(object sender, EventArgs e)
{
txtScore.Clear();
txtScoreTotal.Clear();
txtScoreCount.Clear();
txtAverage.Clear();
txtScore.Focus();
}
Your int array scoreTotalArray is always one element to big. That extra element contains the 0 you want to get rid of ;-)
Clearing the scores can be done by resizing your array to 0.
That said: You should probably consider using a List instead of an int array.

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