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.
Related
I generate my random numbers with the Random num1 = new Random() method. I wanted to know if there was any way to have something like 10 different questions, each corresponding to a possible number. For example, when the random number 1 is generated, I want the question "What is the fastest animal?". I was able to do this quite easily, but every time I did the Console.ReadLine(); right afterward, the question before that changes on me. An example of what this would look like is this:
What is the fastest animal? > and then once I answered, it would show something like this:
An elephant's diet consists mostly of what? cheetah. How can I fix this?
Here is my code:
public class Program
{
public static void Main()
{
string[] incorrectAnswersJediSimple = new string[5];
Random JediS1 = new Random();
int randJediS1 = JediS1.Next(1, 4);
int totalScore = 0;
string JediQ11 = "JediQ11";
switch(randJediS1){
case 1:
JediQ11 = "Who is Luke Skywalker's father? ";
Console.Write(JediQ11);
string JediQ111 = Console.ReadLine();
if (JediQ111.Equals("Darth Vader", System.StringComparison.OrdinalIgnoreCase) || JediQ111.Equals("Vader", System.StringComparison.OrdinalIgnoreCase) || JediQ111.Equals("Anakin Skywalker", System.StringComparison.OrdinalIgnoreCase) || JediQ111.Equals("Anakin", System.StringComparison.OrdinalIgnoreCase)) {
totalScore++;
} else {
incorrectAnswersJediSimple[0] = "#1";
}
break;
case 2:
JediQ11 = "Who is Luke Skywalker's sister? ";
Console.Write(JediQ11);
string JediQ112 = Console.ReadLine();
if (JediQ112.Equals("Princess Leia", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Leia", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Leia Organa", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Leia Skywalker", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Princess Leia Organa", System.StringComparison.OrdinalIgnoreCase) || JediQ112.Equals("Princess Leia Skywalker", System.StringComparison.OrdinalIgnoreCase)) {
totalScore++;
} else {
incorrectAnswersJediSimple[0] = "#1";
}
break;
case 3:
JediQ11 = "What is Darth Vaders real name? ";
Console.Write(JediQ11);
string JediQ113 = Console.ReadLine();
if (JediQ113.Equals("Anakin Skywalker", System.StringComparison.OrdinalIgnoreCase) || JediQ113.Equals("Anakin", System.StringComparison.OrdinalIgnoreCase) || JediQ113.Equals("Ani boi", System.StringComparison.OrdinalIgnoreCase) || JediQ113.Equals("ani", System.StringComparison.OrdinalIgnoreCase)) {
totalScore++;
} else {
incorrectAnswersJediSimple[0] = "#1";
}
break;
case 4:
JediQ11 = "What species is Admiral Ackbar? ";
Console.Write(JediQ11);
string JediQ114 = Console.ReadLine();
break;
case 5:
JediQ11 = "Who is Han Solo's Wookie sidekick? ";
Console.Write(JediQ11);
string JediQ115 = Console.ReadLine();
break;
case 6:
JediQ11 = "What species is Jar Jar Binks? ";
Console.Write(JediQ11);
string JediQ116 = Console.ReadLine();
break;
case 7:
JediQ11 = "On what planet does Luke first find Yoda in the original trilogy? ";
Console.WriteLine(JediQ11);
string JediQ117 = Console.ReadLine();
break;
case 8:
JediQ11 = "Who is Rey's grandfather? ";
Console.Write(JediQ11);
string JediQ118 = Console.ReadLine();
break;
case 9:
JediQ11 = "Who threw Mace Windu out of a window? ";
Console.Write(JediQ11);
string JediQ119 = Console.ReadLine();
break;
case 10:
JediQ11 = "What planet is Jedi Master Plo Koon from? ";
Console.Write(JediQ11);
string JediQ1110 = Console.ReadLine();
break;
default:
JediQ11 = "ERROR";
Console.WriteLine(JediQ11);
Console.Write("\nPress any key to continue...");
string ERROR11 = Console.ReadLine();
break;
}
}
}```
I want to add switch case to not allow the user to write string when entering temperature or when there is nothing to delete it says "there is nothing to delete, go back to menu".
List<string> Temp = new List<string>();
while (true)
{
string val;
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
val = Console.ReadLine();
if (val == "l" || val == "L")
{
Console.WriteLine("add temperature : ");
Temp.Add(Console.ReadLine());
Console.Clear();
}
else if(val == "s" || val == "S")
{
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
}
else if (val == "t" || val == "T")
{
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
}
else
{
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
To control use input you can extract methods, e.g.
private 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("Incorrect syntax, please, try again.");
}
}
then you can put
val = Console
.ReadLine()
.Trim() // Let's be nice and tolerate leading / trailing spaces, e.g. " L "
.ToUpper();
val = val.Substring(0, Math.Max(1, val.Length));
switch (val) {
case "L":
// We read valid integer, turn it to string and out to Temp
Temp.Add(ReadInteger("add temperature : ").ToString());
Console.Clear();
break;
case "T":
int deleteIndex = ReadInteger(
"$"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
if (deleteIndex >= 0 && deleteIndex < Temp.Count)
Temp.RemoveAt(deleteIndex);
else
Console.WriteLine("Index out of range");
break;
...
}
Please check C# reference websites or books before asking questions.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/
Here is the code you wanted, hope this helps you:
List<string> Temp = new List<string>();
while (true)
{
menu:
string val = string.Empty;
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
val = Console.ReadLine();
switch (val.ToLower())
{
case "l":
addTemperature:
Console.WriteLine("add temperature : ");
string temperatureInput = Console.ReadLine();
int temperatureToAddToList;
try
{
temperatureToAddToList = Convert.ToInt32(temperatureInput); //This line trys to convert string variables to integer variables. If string variable includes any character, it will throw an exception.
}
catch (Exception error) //If an exception was thrown, this code block gets activated, which will give out the message you asked for.
{
Console.Clear();
Console.WriteLine("Please enter a number instead of a string!");
goto addTemperature;
}
Temp.Add(temperatureInput.Trim());
Console.Clear();
break;
case "s":
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
break;
case "t":
if (Temp.Count == 0)
{
Console.Clear();
Console.WriteLine("There is nothing to delete, go back to menu.");
goto menu;
}
else
{
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
break;
}
default:
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
I have revised and updated my code example to better solve your problem.
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.
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"));
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"));
}
}