Collecting multiple Variables from one loop - c#

I'm Working on a project for college and have sat here trying to figure out a solution to this problem for a solid 3 hours now. the problem is:
Scenario:
You want to calculate a student’s GPA (Grade Point Average) for a number of classes taken by the student during a single semester.
Inputs:
The student’s name.
Class names for the classes taken by the student.
Class letter grade for the classes taken by the student.
Class credit hours for the classes taken by the student.
Processing:
Accept and process classes until the user indicates they are finished.
Accumulate the number of credit hours taken by the student.
Calculate the total number of “points” earned by the student as:
a. For each class calculate the points by multiplying the credit hours for that class times the numeric equivalent of the letter grade. (A=4.0, B=3.0, C=2.0, D=1.0, F=0)
b. Total all points for all classes.
Calculate the GPA as the total number of “points” divided by the total credit hours.
Output:
Display a nicely worded message that includes the student’s name and the GPA (decimal point number with 2 decimal places) achieved by the student that semester.
What I currently have is:
static void Main(string[] args)
{
String StudentName;
//Error Trapping
try
{
Console.WriteLine("Welcome to The GPA Calculator");
Console.WriteLine("Hit any key to continue...");
Console.ReadKey();
Console.Write("Please enter your name: ");
StudentName = Convert.ToString(Console.ReadLine());
InputGradeInfo();
}
//Error Repsonse
catch (System.Exception e)
{
Console.WriteLine("An error has Occurred");
Console.WriteLine("The error was: {0}" , e.Message);
//Belittle the User
Console.WriteLine("Good Job, you Broke it.");
Console.ReadLine();
}
}
public static double InputGradeInfo()
{
String ClassName;
Char LetterGrade;
Double LetterGradeValue;
Double CreditHours;
Double ValueOfClass;
Console.Write("Please enter the class title: ");
ClassName = Convert.ToString(Console.ReadLine());
Console.Write("Please enter the total credits this class is worth: ");
CreditHours = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the grade letter recived: ");
LetterGrade = Convert.ToChar(Console.ReadLine());
switch (LetterGrade)
{
case 'a': LetterGradeValue = 4;
break;
case 'A': LetterGradeValue = 4;
break;
case 'b': LetterGradeValue = 3;
break;
case 'B': LetterGradeValue = 3;
break;
case 'c': LetterGradeValue = 2;
break;
case 'C': LetterGradeValue = 2;
break;
case 'd': LetterGradeValue = 1;
break;
case 'D': LetterGradeValue = 1;
break;
case 'f': LetterGradeValue = 0;
break;
case 'F': LetterGradeValue = 0;
break;
default: LetterGradeValue = 0;
break;
}
ValueOfClass = CalculateClass(LetterGradeValue, CreditHours);
return ValueOfClass;
}
public static double CalculateClass(double LetterGrade, double CreditHours)
{
Double CreditTotal;
CreditTotal = CreditHours * LetterGrade;
return CreditTotal;
}
The Problem arises for me as to how one would loop info collection, save it to different variable every time and then breaking the loop using user input at the end. We haven't learned about arrays yet so that's off the table. After I have that looped collection down calculating the total GPA and displaying wouldn't be difficult.
Also I haven't learned about created classes yet so I can't use those either

static void Main(string[] args)
{
String StudentName;
//Error Trapping
try
{
Console.WriteLine("Welcome to The GPA Calculator");
Console.WriteLine("Hit any key to continue...");
Console.ReadKey();
Console.Write("Please enter your name: ");
StudentName = Convert.ToString(Console.ReadLine());
List<double> gradeInfoList = new List<double>();
List<double> creditList = new List<double>();
bool brakeLoop = false;
while (!brakeLoop)
{
gradeInfoList.Add(InputGradeInfo(creditList));
Console.WriteLine("Do you want to continue(y/n): ");
brakeLoop = Console.ReadLine() != "y";
}
Console.WriteLine(StudentName + " GPA is: " + gradeInfoList.Sum() / creditList.Sum());
}
//Error Repsonse
catch (System.Exception e)
{
Console.WriteLine("An error has Occurred");
Console.WriteLine("The error was: {0}", e.Message);
//Belittle the User
Console.WriteLine("Good Job, you Broke it.");
Console.ReadLine();
}
}
public static double InputGradeInfo(List<double> creditList)
{
String ClassName;
Char LetterGrade;
Double LetterGradeValue;
Double CreditHours;
Double ValueOfClass;
Console.Write("Please enter the class title: ");
ClassName = Convert.ToString(Console.ReadLine());
Console.Write("Please enter the total credits this class is worth: ");
CreditHours = Convert.ToDouble(Console.ReadLine());
creditList.Add(CreditHours);
Console.Write("Please enter the grade letter recived: ");
LetterGrade = Convert.ToChar(Console.ReadLine().ToUpper());
switch (LetterGrade)
{
case 'A': LetterGradeValue = 4;
break;
case 'B': LetterGradeValue = 3;
break;
case 'C': LetterGradeValue = 2;
break;
case 'D': LetterGradeValue = 1;
break;
case 'F': LetterGradeValue = 0;
break;
default: LetterGradeValue = 0;
break;
}
ValueOfClass = CalculateClass(LetterGradeValue, CreditHours);
return ValueOfClass;
}
public static double CalculateClass(double LetterGrade, double CreditHours)
{
Double CreditTotal;
CreditTotal = CreditHours * LetterGrade;
return CreditTotal;
}
Here you probably want this. You need one while loop to take all the classes, the loop brakes if you say that you don't want to continue or put another input. You make the gradeInfoList with gradeInfoList.Sum() function.
Also your variables should start with small letter, StudentName->studentName !
EDIT:
gpa List is collection which stores all your values which comes from InputGradeInfo().
What Sum() function is doing:
double sum = 0;
foreach(double d in gpa)
{
sum= sum + d; //(or sum+= d;)
}
In other words loop all the elements in gradeInfoList collection and make the sum of them.
About the while loop-> this loop will executes till the condition in the brackets is broken. In this case you can add many classes till you click 'y' at the end. If you click something else from 'y' you will break the loop.
I add another list creditList which you will add as parameter to the InputGradeInfo. In this list you will store every credit per class. At the end you will have gradeInfoList .Sum()/creditList.Sum() and this will give you what you want.

Related

Calculator Transforming Coulomb units freezes unexpletedly

internal class Program
{
static void Main(string[] args)
{
double result = 0;
Console.WriteLine("Welcome to the Physics calculator!");
Console.WriteLine("Please choose one of the following options");
Console.WriteLine("1.Unit Conversions");
Console.WriteLine();
Console.WriteLine("What is the current form of the number you are trying to convert?");
Console.WriteLine("1.Coulomb");
Console.WriteLine("2.mCoulomb");
Console.WriteLine("3.μCoulomb");
Console.WriteLine("4.nCoulomb");
Console.WriteLine("5.pCoulomb");
string answer1 = Console.ReadLine();
double answerbase = 0;
double answerpow = 0;
switch (answer1)
{
case "1":
Console.WriteLine("Please continue to the next part");
answerbase = Convert.ToDouble(Console.ReadLine());
break;
case "2":
Console.WriteLine("Please enter the number: ");
answerbase = Convert.ToDouble(Console.ReadLine());
break;
case "3":
Console.WriteLine("Please enter the number: ");
answerbase = Convert.ToDouble(Console.ReadLine());
break;
case "4":
Console.WriteLine("Please enter the number: ");
answerbase = Convert.ToDouble(Console.ReadLine());
break;
case "5":
Console.WriteLine("Please enter the number: ");
answerbase = Convert.ToDouble(Console.ReadLine());
break;
default:
Console.WriteLine("That is not a valid option!");
break;
}
Console.WriteLine("In which for would you like to convert your number?");
Console.WriteLine("Choose one of the following options");
Console.WriteLine("1.Coulomb");
Console.WriteLine("2.mCoulomb");
Console.WriteLine("3.μCoulomb");
Console.WriteLine("4.nCoulomb");
Console.WriteLine("5.pCoulomb");
string answer2 = Console.ReadLine();
//Console.WriteLine("Please input your number");
//double answer3 = Convert.ToDouble(Console.ReadLine());
double resultconversion = 0;
while (answer1 == "1")
{
if (answer1 == answer2)
{
Console.WriteLine("No conversion neeeded!");
}
else if (answer1 != answer2)
{
switch (answer2)
{
case "2":
answerpow = 10 ^ -3;
resultconversion = Math.Pow(answerbase, answerpow);
break;
case "3":
answerpow = 10 ^ -6;
resultconversion = Math.Pow(answerbase, answerpow);
break;
case "4":
answerpow = 10 ^ -9;
resultconversion = Math.Pow(answerbase, answerpow);
break;
case "5":
answerpow = 10 ^ -12;
resultconversion = Math.Pow(answerbase, answerpow);
break;
}
}
}
while(answer1 == "2")
{
if (answer1 == answer2)
{
Console.WriteLine("No conversion needed");
}
else if (answer1 != answer2)
switch (answer2) //line 107
{
case "1":
answerpow = 10 ^ 3;
resultconversion = answerbase/(10 ^ 3);
break;
case "3":
answerpow = 10 ^ 6;
resultconversion = Math.Pow(answerbase, answerpow);
break;
case "4":
answerpow = 10 ^ 9;
resultconversion = Math.Pow(answerbase, answerpow);
break;
case "5":
answerpow = 10 ^ 12;
resultconversion = Math.Pow(answerbase, answerpow);
break;
}
}
Console.WriteLine($"The result in an int form: {answerbase}^{answerpow}");
Console.WriteLine($"The number {answerbase} is raised to the power of {answerpow}");
Console.WriteLine("The result in decimal for: " + resultconversion);
}
}
The problem that I face is that when I reach line 107 my code freezes and nothing happens. I am not sure what's happening. Please note that the code is incomplete and the working functions as of right now are only the first and half of the second. I am a beginner and I would appreciate if you would not critisise me for not discovering the problem.
I added a while loop so for each answer specific things would happen. But inside the second while loop something seems to be broken inside the first switch case at line 107. When I input the form of the current number as mCoulomb and the form I am trying to convert it to Coulomb the program just freezes.
The problem is simple, you have a while loop on answer1 but you are not modifying it anywhere in your code. and that is the reason it is becoming an infinite loop. you can either add a break at the end of each while loop (you need to check this first). or modify the answer1 so that it may come out of the loop.
Vivek's answer is correct as to what's happening in your program. You should mark his answer as correct.
I'm posting this as a way for you to see how this code can get written.
string unit = "Coulomb";
var factors = new[]
{
new { name = "", magnitude = 0 },
new { name = "m", magnitude = -3 },
new { name = "μ", magnitude = -6 },
new { name = "n", magnitude = -9 },
new { name = "p", magnitude = -12 },
};
string[] header1 = new string[] { "Welcome to the Physics calculator!", "Please choose one of the following options", "1.Unit Conversions", "", "What is the current form of the number you are trying to convert?", };
string[] header2 = new string[] { "In which for would you like to convert your number?", "Choose one of the following options", };
int GetFactorIndex(string[] header)
{
Console.WriteLine(String.Join(Environment.NewLine, header.Concat(factors.Select((x, n) => $"{n + 1}. {x.name}{unit}"))));
return int.Parse(Console.ReadLine()) - 1;
}
int index1 = GetFactorIndex(header1);
Console.WriteLine("Please enter the number: ");
double value = double.Parse(Console.ReadLine());
int index2 = GetFactorIndex(header1);
int magnitude = factors[index1].magnitude - factors[index2].magnitude;
double factor = Math.Pow(10.0, magnitude);
double answer = value * factor;
Console.WriteLine($"The number {value} {factors[index1].name}{unit} is multiplied by {factor}");
Console.WriteLine($"The result in value of: {answer} {factors[index2].name}{unit}");
That's it. I think it is working correctly. Let me know if there are any issues you discover.

Receipt like output in c#

int choice, quanti, decide, total, cash;
double change;
string dcount;
while (true)
{
Console.Clear();
string w = "WELCOME ";
Console.SetCursorPosition((Console.WindowWidth - w.Length) / 2, Console.CursorTop); // for setting string output on center top
Console.WriteLine(w);
Console.WriteLine("");
System.Threading.Thread.Sleep(2000); //time delay
string p = "HERE'S OUR MERCHANDISES! ";
Console.SetCursorPosition((Console.WindowWidth - p.Length) / 2, Console.CursorTop); // for setting string output on center top
Console.WriteLine(p);
System.Threading.Thread.Sleep(2000);//time delay
string[] products = { "[1]BLACKPINK Lightstick ", "[2]DREAMCATCHER Seasons Greetings",
"[3]RED VELVET Summer Package"};
for (int g = 0; g < products.Length; g++)
{
Console.WriteLine(products[g]);
}
Dictionary<int, int> ProductList = new Dictionary<int, int>();
while (true)
{
{
Console.Write("Pick your product: ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("BLACKPINK Lightstick 1500php");
break;
case 2:
Console.WriteLine("DREAMCATCHER Seasons Greetings 920php");
break;
case 3:
Console.WriteLine("RED VELVET Summer Package 980php");
break;
}
Console.WriteLine("Quantity of product: ");
quanti = int.Parse(Console.ReadLine());
if (!ProductList.ContainsKey(choice))
ProductList.Add(choice, quanti);
else
ProductList[choice] += quanti;
System.Threading.Thread.Sleep(2000);//time delay
Console.WriteLine("[1] Add more products \t [2] Pay: ");
decide = int.Parse(Console.ReadLine());
if (decide == 2)
break;
}
}
total = 0;
foreach (int key in ProductList.Keys)
switch (key)
{
case 1:
total += ProductList[key] * 1500;
break;
case 2:
total += ProductList[key] * 920;
break;
case 3:
total += ProductList[key] * 980;
break;
default:
total += 0;
break;
};
Console.WriteLine("To Pay: " + total);
Console.Write("Cash: ");
cash = Convert.ToInt32(Console.ReadLine());
Console.Write("Discount[s]suki [v]voucher: ");
dcount = Console.ReadLine();
if (dcount == "s")
{
change = (cash - total) - 0.7;
Console.WriteLine("Change: " + change);
}
else if (dcount == "v")
{
change = cash -(total - 0.5) ;
Console.WriteLine("Change: " + change);
}
else
{
change = cash- (total - 0.7) ;
Console.WriteLine("Change: " + change);
}
Console.WriteLine("Another shopping? [1]Yes [2] No");
choice = int.Parse(Console.ReadLine());
if (choice == 2)
break;
}
}
}
}
Good day, I'm doing a project for school. I've already asked earlier about my code and someone help me, thanks to him, unfortunately I still have a problem with my code. After the users inputs and giving her a change, it was supposed to output a receipt like, wherein it contains users purchased products. I've tried outputting the variables that have been used in acquiring users input but to my dismay, it can only output the user's first input product, it can't Output all the users purchase. The receipt like output was supposed to contain the user's products purchased, quantity of each product, total, cash, discount and change in horizontal line/tabular.
Quick way of printing out products and quantity for each would be to put after dcount = Console.ReadLine(); something like:
foreach(var entry in ProductList)
{
Console.WriteLine(products[entry.Key].Substring(3) + "......." + entry.Value);
}
I'll leave the amount of dots and cursor position to You.
Also, when dealing with currency it's better to use decimal due to higher precision (maybe not needed in this example.) And try to use Math.Round() function when displaying money amount - limit decimal places.

Part of method not running

static void getGrades()
{
Console.WriteLine("How many grade level classes are you taking?");
int standardNumber = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("How many honors level classes are you taking?");
int honorsNumber = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("How many AP level classes are you taking?");
int apNumber = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("Enter your letter grades when prompted.");
Console.WriteLine("=======================================");
for (int a = 1; a == standardNumber; a++)
{
int num = 1;
Console.WriteLine("Enter letter grade for honors class {0}:", num);
switch (num)
{
case 1:
string class1 = Console.ReadLine();
break;
case 2:
string class2 = Console.ReadLine();
break;
case 3:
string class3 = Console.ReadLine();
break;
case 4:
string class4 = Console.ReadLine();
break;
default:
break;
}
Console.WriteLine();
}
}
I'm trying to call this method to collect number of classes and grade letters from a mix of 4 classes. When I call the method, the first part (below) executes fine.
Console.WriteLine("How many grade level classes are you taking?");
int standardNumber = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("How many honors level classes are you taking?");
int honorsNumber = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("How many AP level classes are you taking?");
int apNumber = int.Parse(Console.ReadLine());
However, the rest of the code (below) does not execute.
Console.WriteLine();
Console.WriteLine("Enter your letter grades when prompted.");
Console.WriteLine("=======================================");
for (int a = 1; a == standardNumber; a++)
{
int num = 1;
Console.WriteLine("Enter letter grade for honors class {0}:", num);
switch (num)
{
case 1:
string class1 = Console.ReadLine();
break;
case 2:
string class2 = Console.ReadLine();
break;
case 3:
string class3 = Console.ReadLine();
break;
case 4:
string class4 = Console.ReadLine();
break;
default:
break;
}
Console.WriteLine();
}
}
Does anyone know why this might be happening. Thanks in advance
According to your logic, if you enter the input standardNumber as 1 only it will run these lines,
for (int a = 1; a == standardNumber; a++)
{
int num = 1;
}
btw, You dont need a for loop for that.
EDIT:
You need to store the inputs in a collection and do a loop on that
static void Main(string[] args)
{
List<int> inputs = new List<int>();
Console.WriteLine("How many grade level classes are you taking?");
int standardNumber = int.Parse(Console.ReadLine());
inputs.Add(standardNumber);
Console.WriteLine();
Console.WriteLine("How many honors level classes are you taking?");
int honorsNumber = int.Parse(Console.ReadLine());
inputs.Add(honorsNumber);
Console.WriteLine();
Console.WriteLine("How many AP level classes are you taking?");
int apNumber = int.Parse(Console.ReadLine());
inputs.Add(apNumber);
Console.WriteLine();
Console.WriteLine("Enter your letter grades when prompted.");
Console.WriteLine("=======================================");
for (int i = 0; i < inputs.Count; i++)
{
Console.WriteLine("Enter letter grade for honors class {0}:", inputs[i]);
switch (i)
{
case 1:
string class1 = Console.ReadLine();
break;
case 2:
string class2 = Console.ReadLine();
break;
case 3:
string class3 = Console.ReadLine();
break;
case 4:
string class4 = Console.ReadLine();
break;
default:
break;
}
Console.WriteLine();
}
Console.Read();
}
Your method contains these two lines in a row:
int apNumber = int.Parse(Console.ReadLine());
Console.WriteLine();
There are two ways that it's possible for the first line to execute, but the second line not to:
The method call Console.ReadLine() never returns because the user never presses "enter".
Either the method Console.ReadLine or the method int.Parse throws an exception.
My guess is that int.Parse is throwing an exception.
A more theoretical answer:
If I'm not mistaken, when the code that I quoted runs, one of the following must happen, always, no matter what:
The first line continues executing forever.
The first line throws an exception.
The thread is terminated before the second line executes.
The first line returns and the second line executes.
If the last thing doesn't happen, one of the other things must be happening.

c# switch loop, adding up total for each case

I have 2 codes that I want to combine into 1 and am having a lot of trouble doing it. The code should ask for the group number then their donation amount and loop back until they press 0. Once they press 0 it should show the total for all groups. Here are the 2 different codes
code 1
using System;
public class TotalPurchase
{
public static void Main()
{
double donation;
double total = 0;
string inputString;
const double QUIT = 0;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
while(donation != QUIT)
{
total += donation;
Console.WriteLine("Enter next donation amount, or " +
QUIT + " to quit ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
}
Console.WriteLine("Your total is {0}", total.ToString("C"));
}
}
code 2
using System;
namespace donate
{
class donate
{
public static void Main()
{
begin:
string group;
int myint;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
goto begin;
default:
Console.WriteLine("Incorrect grade number.", myint);
goto begin;
}
}
}
}
So basically I want to find the total for each group using the 2nd code.
Any help would be greatly appreciated.
Don't use goto like that. Just use another while loop like you did in the first code segement.
It would be much more concise to say:
if (myInt > 3 && myInt < 7) { ... }
instead of using that switch statement.
Basically your code for summing up the donation amount does the trick, so just stick that inside a similar loop that handles what the group number is. If you do this you're going to want to use a different input to signify the end of donations vs the end of input altogether. It would be confusing if the application said "Enter 0 to quit input", followed by "Enter 0 to quit donation input".
You are very close with Code 2. If you put Code 2 inside while loop it works!
The only code I have written for you here is declared myint outside the while loop and initialised it to a non-zero value.
double total = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
total += donation;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Your total is {0}", total.ToString("C"));

C# How do you count the number of inputs to find the average in a switch loop?

Here is my loop that asks for the group number then the donation. I'm wondering how to count the number of donations to find the average for each group.
using System;
public class TotalPurchase
{
public static void Main()
{
double total4 = 0;
double total5 = 0;
double total6 = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
break;
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4 += donation4;
break;
case 5:
double donation5;
string inputString5;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString5 = Console.ReadLine();
donation5 = Convert.ToDouble(inputString5);
total5 += donation5;
break;
case 6:
double donation6;
string inputString6;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString6 = Console.ReadLine();
donation6 = Convert.ToDouble(inputString6);
total6 += donation6;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Grade 4 total is {0}", total4.ToString("C"));
Console.WriteLine("Grade 5 total is {0}", total5.ToString("C"));
Console.WriteLine("Grade 6 total is {0}", total6.ToString("C"));
}
}
Any help would be appreciated.
Not sure if I fully understand your question -- but you could just add a simple counter for each group:
int donations4 = 0;
int donations5 = 0;
int donations6 = 0;
And then increment that counter in each of your switch cases, ex:
switch(myInt)
{
case 4:
...
donations4++;
break;
case 5:
...
donations5++;
break;
case 6:
...
donations6++;
break;
}
Then when you're done - simply do the math to find the average.
Although this is probably the simplest way, a better way would be to treat each group as its own object, and have the object internally track the # of donations, as well as the sum and average.
-- Dan
using System;
public class TotalPurchase
{
public static void Main()
{
double total4 = 0;
double total5 = 0;
double total6 = 0;
int numberOfInputForTotal4 = 0;
int numberOfInputForTotal5 = 0;
int numberOfInputForTotal6 = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
break;
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4 += donation4;
numberOfInputForTotal4++;
break;
case 5:
double donation5;
string inputString5;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString5 = Console.ReadLine();
donation5 = Convert.ToDouble(inputString5);
total5 += donation5;
numberOfInputForTotal5++;
break;
case 6:
double donation6;
string inputString6;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString6 = Console.ReadLine();
donation6 = Convert.ToDouble(inputString6);
total6 += donation6;
numberOfInputForTotal6++;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Grade 4 total is {0}", total4.ToString("C"));
Console.WriteLine("Grade 5 total is {0}", total5.ToString("C"));
Console.WriteLine("Grade 6 total is {0}", total6.ToString("C"));
Console.WriteLine("Grade 4 average is {0}", (total4 / numberOfInputForTotal4).ToString("C"));
Console.WriteLine("Grade 5 average is {0}", (total5 / numberOfInputForTotal5).ToString("C"));
Console.WriteLine("Grade 6 average is {0}", (total6 / numberOfInputForTotal6).ToString("C"));
}
}
As you can see, there are 3 extra variables (one for each group) that can be used to figure out the number of inputs provided. Using that you can divide the total for each group by the number of input in each group separately.
Just declare count for each group as well as total and increment in the case statement:
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4 += donation4;
count4++; // HERE!!!!
break;
Alternatively, you can use List<int> which will calculate your average as well:
List<int> list4 = new List<int>();
and
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
list4.Add(donation4);
break;
and
Console.WriteLine(list4.Average());
Just keep track of the count yourself with another variable. count4, count5, etc.
For bonus points in your homework assignment:
1) Sanitize your group number input - ie check to see if the user typed in a valid number.
2) Don't call the variable myInt. Call it groupNum, or something that describes the function, not the implementation of the variable.
3) Use an array for donation totals and counts
ie,
int[] donationCount= new int[MAX_GROUP+1]; // figure out yourself why the +1
int[] donationTotal= new int[MAX_GROUP+1];
// initialize donationCount and donationTotal here
then in your loop (don't even need switch):
++donationCount[groupNum];
donationTotal[groupNum] += donationAmount; // did you notice that you moved the reading of donationAmount out of the switch?
I would go with changing your doubles to List and using the Sum() and Average() methods on your Lists at the end. Your code would look like this after this change.
using System;
using System.Collections.Generic;
using System.Linq;
public class TotalPurchase
{
public static void Main()
{
List<double> total4 = new List<double>();
List<double> total5 = new List<double>();
List<double> total6 = new List<double>();
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
break;
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4.Add(donation4);
break;
case 5:
double donation5;
string inputString5;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString5 = Console.ReadLine();
donation5 = Convert.ToDouble(inputString5);
total5.Add(donation5);
break;
case 6:
double donation6;
string inputString6;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString6 = Console.ReadLine();
donation6 = Convert.ToDouble(inputString6);
total6.Add(donation6);
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
if(total4.Count > 0)
Console.WriteLine("Grade 4 total is {0}; Average {1}", total4.Sum().ToString("C"), total4.Average().ToString("C"));
if(total5.Count >0)
Console.WriteLine("Grade 5 total is {0}; Average {1}", total5.Sum().ToString("C"), total5.Average().ToString("C"));
if (total6.Count > 0)
Console.WriteLine("Grade 6 total is {0}; Average {1}", total6.Sum().ToString("C"), total6.Average().ToString("C"));
}
}

Categories