Calculate total and average sales - c#

The assignment is as follows:
Total Sales
Use the attached file named Sales.txt. Create an application that
reads the file’s content into an array of double or decimal
displays the array’s content in a ListBox control,
calculates the total of the array’s values, average sales, largest sales, smallest sales
Display the Total Sales, Average sales, Highest Sales and Smallest Sales
Form should look similar to the following:
How do I get the data to display the Total/Average/High/Low Sales part of the image to display properly by typing the corresponding code?
I'd like to do this on my own so if you could provide an example that might relate to what I am doing that would really help.
Here's what I've been able to type up so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Total_Sales
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void displayButton_Click(object sender, EventArgs e)
{
//declaring array
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
//varible to hold amount stored in array
int count = 0;
decimal additionHolder = 0;
//declaring streamreader
StreamReader inputFile;
//opening the sales file
inputFile = File.OpenText("../../Sales.txt");
try
{
//pull contents from file into array while there is still items
//to pull and the array isnt full
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
count++;
}
//close the file
inputFile.Close();
//display contents in listbox
for (int index = 0; index < count; index++)
{
ListBox.Items.Add(sales[index]);
}
//add all the values
for (int index = 0; index < sales.Length; index++)
{
additionHolder += sales[index];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Here are two solutions. The first using an array, the second using a List. In both example's I presume that the textboxes for total, average, min and max sales are called TotalSales, AverageSales, MinSales and MaxSales.
private void displayButton_Click(object sender, EventArgs e)
{
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
int count = 0;
decimal totalSales, averageSales, minSales, maxSales;
StreamReader inputFile;
inputFile = File.OpenText("../../Sales.txt");
try
{
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
minSales = count == 0 ? sales[count] : Math.Min(minSales, sales[count]);
maxSales = count == 0 ? sales[count] : Math.Max(maxSales, sales[count]);
totalSales += sales[count];
ListBox.Items.Add(sales[count]);
count++;
}
inputFile.Close();
averageSales = totalSales / sales.Length;
TotalSales.Text = totalSales;
AverageSales.Text = averageSale;
MinSales.Text = minSales;
MaxSales.Text = maxSales;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Using a List and Linq:
private void displayButton_Click(object sender, EventArgs e)
{
List<decimal> sales = new List<decimal>(); // notice: no size limitation
StreamReader inputFile;
inputFile = File.OpenText("../../Sales.txt");
try
{
while (!inputFile.EndOfStream)
{
var sale = decimal.Parse(inputFile.ReadLine());
sales.Add(sale);
ListBox.Items.Add(sale);
}
inputFile.Close();
TotalSales.Text = sales.Sum();
AverageSales.Text = sales.Average();
MinSales.Text = sales.Min();
MaxSales.Text = sales.Max();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As you can see this code is much more concise.
BTW, I wrote this code without Visual Studio at hand so it might contain some typo's.

After you read values from file just use Linq methods and set Text property of yours TextBox controls.
var total = sales.Sum();
var avg = sales.Average();
var min = sales.Min();
var max = sales.Max();
totalTextBox.Text = total.ToString(); //example for TextBox named totalTextBox
remember to add using :)
using System.Linq;

Related

When executing second for loop into listbox program populates no data

so the assignment is to read from the student file into an array and read into the answer key array, compare the two and output a grade based on the array comparison.
the issue i'm having is that when i try to load the answer key into it's array it's like its not even getting the data, because all the questions output as wrong.
below is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AshleyBrown_CPT185A01S_Chapter7Lab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//variables
private const int SIZE = 20; //current # of q's on test
private int index = 0, count = 1; //counter variables
private int wrong = 0, right = 0; //grade variables
these are the arrays that are used for the answers:
//arrays
private char[] studentAnswers = new char[SIZE];
private char[] answerKey = new char[SIZE];
private void calculateBtn_Click(object sender, EventArgs e)
{
//prevents any file errors
try
{
ReadStudentFile();
ReadAnswerKey();
CompareAnswers();
}
catch
{
MessageBox.Show("File doesn't exist or has the wrong name.");
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
//Clear Form
studentAListBox.Items.Clear();
correctAListBox.Items.Clear();
wrongAListBox.Items.Clear();
incorrectBox.Text = "";
correctBox.Text = "";
percentBox.Text = "";
}
private void exitBtn_Click(object sender, EventArgs e)
{
//close program
Close();
}
method for reading the student file that works:
private void ReadStudentFile()
{
//Stream Reader Setup
StreamReader studentFile;
studentFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Student File.txt");
//Read Student Answers into studentAnswers Array
while (index < studentAnswers.Length && !studentFile.EndOfStream)
{
studentAnswers[index] = char.Parse(studentFile.ReadLine());
index++;
}
//Close Student Answer file
studentFile.Close();
//Display Student Answers
foreach (char answer in studentAnswers)
{
studentAListBox.Items.Add(count + ". " + answer.ToString());
count++;
}
}
method for reading answer key that populates with no data:
private void ReadAnswerKey()
{
//Stream Reader Setup
StreamReader answerFile;
answerFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Answer Key.txt");
//Read Answer Key in answerKey Array
while (index < answerKey.Length && !answerFile.EndOfStream)
{
answerKey[index] = char.Parse(answerFile.ReadLine());
index++;
}
//Close answer key file
answerFile.Close();
//clear count
count = 1;
//display answer key in correct answer list box
foreach (char key in answerKey)
{
correctAListBox.Items.Add(count + ". " + key.ToString());
count++;
}
}
private void CompareAnswers()
{
//reset count
count = 1;
for (index = 0; index < answerKey.Length; index++)
{
//determine if answer is right
if (studentAnswers[index] != answerKey[index])
{
wrongAListBox.Items.Add(count + ". " + answerKey[index]);
wrong++;
count++;
}
}
//fail display
if (wrong > 5)
{
MessageBox.Show("Student has failed");
}
//calculations
double pointPerQ = 5;
double wrongTotal = wrong;
double wrongPointTotal = wrong * pointPerQ;
double grade = 100 - wrongPointTotal;
//output grade information
incorrectBox.Text = wrong.ToString();
correctBox.Text = right.ToString();
percentBox.Text = grade.ToString("p0");
}
}
}
this is the current output from running the program, I did double check the file names and contents as well.
output of current code
One issue that I saw in code is using of index in multiple while loops without previously assigning to 0.
I suggest using of local variables(variable which exists only in the current block of code).
Also in my opinion it will be good to declare and initialize new variable in for-loop like this:
for(int index = 0; index < answerKey.Length; index++)
{
// your code
}
it will be more readable and easier if you want later to separate loops in methods or move in service or helper.

Cannot get int to be displayed in text box for dice roller app

I'm trying to get back into programming and I'm having trouble getting the final int answers into the text boxes at the end. It has been a few years since I've coded, so if I messed up big time, please let me know.
{
int dice_total;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
string Succ;
string Comp;
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
Succ = succ_num.ToString();
Comp = comp_num.ToString();
}```
[your text box name].Text=[some int].ToString();
For example:
label1.Text = product.BuyingPrice.ToString();
I can't seem to get it count up the successes. For those who don't know, WoD has you roll d10s and you are given a difficulty. You have to roll that difficulty number or higher to get successes. If there are more (or equal) 1s than total successes, its a complication. This isn't even including code for when you roll a 10 (which has you roll again while still counting as a success).
Ex. Roll 5d10s with a difficulty of 6
6, 8, 10, 1, 1 = 3 success
Roll again for the 10: 1
Total: 3 successes and a complication
using Accord.Math.Distances;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Roller
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int dice_total;
int dice_add;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
public void button1_Click(object sender, EventArgs e)
{
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
for (dice_add = 0; dice_add < dice_total; dice_add++)
{
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
}
Succ.Text = succ_num.ToString();
Comp.Text = comp_num.ToString();
}
}
}

How to calculate the "average" value , "highest" value , and "Lowest" value in an array? C#

PART 1: I am to create a program that that reads a file’s contents into an array, and displays the array’s contents in a ListBox control, and calculates and displays the total of the array’s values. - DONE THAT PART
PART 2: Calculate the average, Highest, and Lowest value and display them in a Label control.
I'm new to coding so I couldn't do much, I turn to stack overflow for help
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace SalesAnalysis
{
public partial class SalesAnalysisApplication : Form
{
public SalesAnalysisApplication()
{
InitializeComponent();
}
private void salesAnalysisButton_Click(object sender, EventArgs e)
{
//declaring array
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
//varible to hold amount stored in array
int count = 0;
//declaring streamreader
StreamReader inputFile;
//opening the sales file
inputFile = File.OpenText("Sales.txt");
try
{
//pull contents from file into array while there is still
// items to pull and the array isnt full
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
count++;
}
//close the file
inputFile.Close();
//display contents in listbox
for (int index = 0; index < count; index++)
{
salesListBox.Items.Add(sales[index]);
}
//Calculate the sum of all values
for (int index = 0; index < sales.Length; index++)
{
totalSales += sales[index];
}
//display total of all values
salesListBox.Items.Add("Total =" + totalSales);
//Determine the average sales from the array
for (int index = 0; index < sales.Length; index++)
{
//calculate the average
averageSales = totalSales / 7;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Clear_Click(object sender, EventArgs e)
{
//Clear all fields
salesListBox.Items.Clear();
averageResultsLabel.Text = "";
highestResultsLabel.Text = "";
lowestResultsLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
//close form
this.Close();
}
}
}
You can use linq to do this for example:
var list=Enumerable.Range(0,1000);
var average = list.Average();
var highest = list.Max()
var smallest= list.Min()
var total= list.Sum()
P.S do not forget to add using System.Linq;
The non-linq approach.
You have a sales.Length and a totalSales. Therefore, you have an averageSales.
For max & min, while you are in the for loop
for (int index = 0; index < sales.Length; index ++
{
if (sales
}
simply assign the value based on an if statement. Something like:
if (sales[index] > highestSales)
{
highestSales = sales[index];
}
if (sales[index] < lowestSales)
{
lowestSales = sales[index];
}
First convert u r Decimal array to List.
List<decimal> lst = sales.OfType<decimal>().ToList(); // Convert to List.
Then Follow Linq Operations.
lst.Average(); lst.Min();
In case you prefer good old loop (and no Linq), you can try File.ReadLines and foreach:
decimal max = 0;
decimal min = 0;
decimal sum = 0;
int count = 0;
foreach(string line in File.ReadLines("Sales.txt")) {
decimal value = decimal.Parse(line);
salesListBox.Items.Add(value);
if (count == 0 || value > max)
max = value;
if (count == 0 || value < min)
min = value;
sum += value;
count += 1;
}
decimal average = sum / count;
averageResultsLabel.Text = average.ToString("f2");
highestResultsLabel.Text = max.ToString();
lowestResultsLabel.Text = min.ToString();
Here we don't have to create any array at all. If you insist on having array a simple Linq can help
decimal[] sales = File
.ReadLines("Sales.txt")
.Select(line => decimal.Parse(line))
.ToArray();
And foreach will be
foreach(decimal value in sales) {
salesListBox.Items.Add(value);
...
}

getting a value from an image in C#

I am creating a project where random images show when i click a button and the total of the images (dice) will have to be guessed. I already have down the random image generating and keeping track of the persons amount of rolls. However; I cant figure out how to make a dice (image) have a certain value. Like dice 5 shows and has a value of 4. The person puts there guess in the guessBx and clicks on the guessBtn and it will pop up if they are correct or not.
Here is my code as of now:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PetalsAroundTheRose
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int a = 0;
int diceRoll;
int diceImage;
int diceValue;
private void btnRoll_Click_1(object sender, EventArgs e)
{
Random random = new Random();
picBx1.Image = imageList1.Images[random.Next(1, 6)];
picBx2.Image = imageList1.Images[random.Next(1, 6)];
picBx3.Image = imageList1.Images[random.Next(1, 6)];
picBx4.Image = imageList1.Images[random.Next(1, 6)];
a++;
txtBxRolls.Text = a.ToString();
//each dice seperate
//dice 1
diceRoll = 1;
diceImage = imageList1.Images[(1)];
diceValue = 0;
//dice 2
diceRoll = 1;
diceImage = imageList1.Images[(2)];
diceValue = 0;
//dice 3
diceRoll = 1;
diceImage = imageList1.Images[(3)];
diceValue = 2;
//dice 4
diceRoll = 1;
diceImage = imageList1.Images[(4)];
diceValue = 0;
//dice 5
diceRoll = 1;
diceImage = imageList1.Images[(5)];
diceValue = 4;
}
private void guessBx_TextChanged_1(object sender, EventArgs e)
{
}
}
}
On my design I have btnRoll for rolling the dice. guessBx for entering the guess, btnGuess, txtBxCorrect for the amount correct they got, and txtBxResult to say if they are correct or not
The images are in an imageList
Firstly i create a class with these two properties
public class Dice
{
public int Indexer { get; set; }
public string PhotoPath { get; set; }
public Dice(int indexer, string photoPath)
{
Indexer = indexer;
PhotoPath = photoPath;
}
}
After that i put in my form the picture boxes and then i created two methods
the first one:
public void SetUp()
{
for (int i = 1; i <= 6; i++)
{
temp = random.Next(1, 6);
dice = new Die(temp, "C:\\Users\\giorg\\Desktop\\dice\\dice" + temp + ".PNG");
dices.Add(dice); // list<Dice> dices = new list<Dice>();
}
}
and the second one:
public void RollDices()
{
//this is not necessary but if you want to keep a sum of dices keep
//it
var count = 0;
foreach (var dice in dices)
{
count += dice.Indexer;
}
//pictureboxes 2-7 are guess boxes
if(textBox2.Text.Equals(dices[0].Indexer.ToString()))
pictureBox1.Image = Image.FromFile(dices[0].PhotoPath);
if (textBox3.Text.Equals(dices[1].Indexer.ToString()))
pictureBox2.Image = Image.FromFile(dices[1].PhotoPath);
if (textBox4.Text.Equals(dices[2].Indexer.ToString()))
pictureBox3.Image = Image.FromFile(dices[2].PhotoPath);
if (textBox5.Text.Equals(dices[3].Indexer.ToString()))
pictureBox4.Image = Image.FromFile(dices[3].PhotoPath);
if (textBox6.Text.Equals(dices[4].Indexer.ToString()))
pictureBox5.Image = Image.FromFile(dices[4].PhotoPath);
if (textBox7.Text.Equals(dices[5].Indexer.ToString()))
pictureBox6.Image = Image.FromFile(dices[5].PhotoPath);
}
Put these two methods to your button click event and you are ok...
Inform me if you are ok with this approach.

Why is my C# code coming up with zero's in message box upon clicking exit?

I am trying to get my message box to show the invoice subtotals stored in my array...5 of them to show in a message box using the foreach method.
I am supposed to input a wage and it then does some calculation and stores the subtotal value into the array. I declared an array and index called decArray and intIndex.
Can anyone tell me what I'm missing or doing wrong?
Thank you in advance!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace InvoiceTotal
{
public partial class frmInvoiceTotal : Form
{
public frmInvoiceTotal()
{
InitializeComponent();
}
// TODO: declare class variables for array and list here
decimal[] decArray = new decimal[5];
int intIndex = 0;
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
if (txtSubtotal.Text == "")
{
MessageBox.Show(
"Subtotal is a required field.", "Entry Error");
}
else
{
decimal subtotal = Decimal.Parse(txtSubtotal.Text);
if (subtotal > 0 && subtotal < 10000)
{
decimal discountPercent = 0m;
if (subtotal >= 500)
discountPercent = .2m;
else if (subtotal >= 250 & subtotal < 500)
discountPercent = .15m;
else if (subtotal >= 100 & subtotal < 250)
discountPercent = .1m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
discountAmount = Math.Round(discountAmount, 2);
invoiceTotal = Math.Round(invoiceTotal, 2);
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString();
txtTotal.Text = invoiceTotal.ToString();
for (intIndex = 0; intIndex <= decArray.Length - 1; intIndex++)
{
DecArray[intIndex] = InvoiceTotal
}
}
else
{
MessageBox.Show(
"Subtotal must be greater than 0 and less than 10,000.",
"Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show(
"Please enter a valid number for the Subtotal field.",
"Entry Error");
}
txtSubtotal.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
// TODO: add code that displays dialog boxes here
string totalstring = "";
foreach (decimal value in decArray)
{
totalstring += value + "\n";
MessageBox.Show(totalstring + "\n", "Order Totals");
}
this.Close();
}
}
}
You are never assigning to your decArray (e.g. decArray[0] = n;)
If you add a count variable to increment your arrays count then you could add more than the one amount. You would also want to allow the array to resize as needed.
decimal[] decArray = new decimal[5];
int _indexCount = 0;
private void btnCalculate_Click(object sender, EventArgs e)
{
...
if (decArray.Count() == _indexCount)
{
var elementHolder = decArray;
decArray = new T[(decArray.Length + 1) * 2];
for (int i = 0; i < elementHolder.Length; i++)
{
decArray[i] = elementHolder[i];
}
}
decArray[_indexCount] = invoiceTotal;
_indexCount++;
}
Something like that should work.
Edit:
Reason you get so many Messages is because the MessageBox.Show() is inside the foreach loop just put it outside the loop and you will only see one.
private void btnExit_Click(object sender, EventArgs e)
{
// TODO: add code that displays dialog boxes here
string totalstring = "";
foreach (decimal value in decArray)
{
totalstring += value + "\n";
}
MessageBox.Show(totalstring + "\n", "Order Totals");
this.Close();
}

Categories

Resources