Getting Values from User - c#

hello please i am having issues getting the values of a system generated variables. here is the code for the getting the values from user;
public void DetailsRate()
{
begin1:
Console.WriteLine("\n \t Rate the Acting on a scale of 0 to 5");
RateActing = int.Parse(Console.ReadLine());
switch (RateActing)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
Console.WriteLine("\n you have rated the action of the movie {0}", RateActing);
break;
default:
Console.WriteLine("you have selected the wrong choice {0}", RateActing);
goto begin1;
}
begin2:
Console.WriteLine("\n \t Rate the music of the movie on a scale of 0 to 5");
RateMusic = int.Parse(Console.ReadLine());
switch (RateMusic)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
Console.WriteLine("you have rated the music of the movie {0}", RateMusic);
break;
default:
Console.WriteLine("you have selected the wrong choice {0}", RateMusic);
goto begin2;
}
}
I called the inputed values into this piece of code
public double getoverallRate(double rateact, double ratemus)
{
double totrate = 0;
rateact = RateActing * 0.25;
ratemus = RateMusic * 0.15;
totrate = (rateact + ratemus);
return totrate;
}
and here is the main method
static void Main(string[] args)
{
MovieRating MR = new MovieRating();
MR.DetailsRate();
MovieRating MT = new MovieRating();
double totrate = MT.getoverallRate(1, 2);
Console.WriteLine("total rate is {0}", totrate);
Console.ReadKey();
}
Please what Im i missing the value of totrate is just giving me 0. please help me.

First get rid of the goto statements. At a quick glance you could write this:
static void Main(string[] args)
{
double RateActing = -1;
double RateMusic = -1;
RateActing = GetMovieRating(RateActing);
RateMusic = GetMovieMusicRating(RateMusic);
double totrate = getoverallRate(RateActing, RateMusic);
Console.WriteLine("total rate is {0}", totrate);
Console.ReadKey();
}
private static double GetMovieRating(double RateActing)
{
do
{
Console.WriteLine("\n \t Rate the Acting on a scale of 0 to 5");
double.TryParse(Console.ReadLine(), out RateActing);
}
while (RateActing < 0 || RateActing > 5);
Console.WriteLine("\n you have rated the action of the movie {0}", RateActing);
return RateActing;
}
private static double GetMovieMusicRating(double RateMusic)
{
do
{
Console.WriteLine("\n \t Rate the music of the movie on a scale of 0 to 5");
double.TryParse(Console.ReadLine(), out RateMusic);
}
while (RateMusic < 0 || RateMusic > 5);
Console.WriteLine("\n you have rated the music of the movie {0}", RateMusic);
return RateMusic;
}
public static double getoverallRate(double rateact, double ratemus)
{
rateact *= 0.25;
ratemus *= 0.15;
return rateact + ratemus;
}

There are lots of problems here - almost enough to start over!
First: Never use goto - there are better ways to construct your program flow.
Second: Your method getoverallRate takes less parameters (2) than what you're passing in (5) so this shouldn't even build.
Third: You are referencing three additional variables in getoverallRate that look like they should be local variables but they are not defined anywhere. Should these be passed in like the usage implies in Main.
Fourth: you are passing in values in variables rateact and ratemus but you are overwriting them immediately with your calculations.
Fifth: It would make more sense to me if you were passing in the input values from the user to this method along with any others you need. You should not be using Global variables from user input in any method that calculates values and returns a result. You should always pass in whatever is needed by the calculation.
Sixth: What is the point of the MR declaration and what does DetailsRate do?

Related

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.

Temperature converter

Im am trying to solve an issue.
My teacher wants us to do a C# console with temperature converter from Celsius to Fahrenheit and switch. The problem is I continue getting errors in my coding and I don't know where I started wrong in order to get completely lost. Just to mention I am in the beginning and I would appreciate some help.
We should write a program that displays a list of temperatures in Celsius converted to Fahrenheit and vice versa. A menu is provided for the user to choose the type of conversions: The menu should repeat until the user chooses 0 to exit.
When option 1 is chosen, the program calculates and displays a list of values between 0 and 212 degrees in Fahrenheit converted to Celsius degrees as shown in the next image When option 2 is selected, the program lists values from 0 to 100 Celsius converted to Fahrenheit degrees.
This is my beginning:
using System;
namespace TempconverterA2
{
class TemperatureConverter
{
public void Start()
{
Console.WriteLine("**************************************");
Console.WriteLine("\t MAIN MENU");
Console.WriteLine("**************************************");
Console.WriteLine(" Convert Fahrenheit to Celsius : 1");
Console.WriteLine(" Convert Celsius to Farenheit : 2");
Console.WriteLine(" Exit the Converter : 0");
Console.WriteLine("**************************************");
Console.WriteLine("\nYour choice: ");
switch (choice)
{
case 1:
CalculateFarenheitToCelsius(F = 9 / 5 * C + 32);
break;
case 2:
CalculateCelsiusToFarenhet(C = 5 / 9 * (F - 32));
case 0: //do nothing (exists to loop)
break;
default:
Console.WriteLine("Invalid option. Choose between 0 and 2.");
break;
} while (choice != 0) ;
public void CalculateCelsiusToFarenhet()
{
double convertedValue = 0;
stringtextOut = string.Empty;
for (int i= 0, i <= 100; i += 5)
{
convertedValue = CalculateCelsiusToFarenhet(i);
textOut = string.Format("{0,16:f2} C = {1,6:f2} F", i, convertedValue);
Console.WriteLine(textOut);
}
Console.WriteLine();
}
}//End of Start
This is not doing what you think it is:
switch (choice)
{
// case statements removed for brevity
} while (choice != 0);
It is actually doing this:
switch (choice)
{
}
while (choice != 0)
{
// infinite loop if choice != 0
}
This is because switch is a control block and while is a separate control block.

Calculating average of sequential numbers in c#

I want to create sequential numbers and when the user inputs "0", it should stop and keep the numbers in the memory and then ask the user whether to show the total of these numbers or show the average. The total looks good but when I choose average my console is not responding, it crashes.
using System;
class ETA11
{
public static int Main()
{
ETA11_3();
return 0;
}
public static void ETA11_3()
{
int number = 0, total = 0, option = 0, counter = 0, average = 0;
do
{
Console.WriteLine("Input a number (zero for stop): ");
number = Int16.Parse(Console.ReadLine());
total += number;
if (number == 0) break;
} while (option != 2);
Console.WriteLine("Choose an option: ");
Console.WriteLine("1 - Total");
Console.WriteLine("2 - Average");
counter++;
option = Int16.Parse(Console.ReadLine());
switch (option)
{
case 1:
Console.WriteLine("Total: {0}", total);
break;
case 2:
Console.WriteLine("Total: {0}", total / number);
break;
default:
Console.WriteLine("Invalid Option");
break;
}
}
}
when you choose option 2, you are dividing 0
Console.WriteLine("Total: {0}", total / number);
I believe you wanted to divide by counter
Console.WriteLine("Total: {0}", total / (decimal) counter);
however, you need to put counter++ inside your whileloop too
As Neverever mentioned, you were dividing by number which was 0 causing a DividedByZeroException. I also incorporated the correct counter into your loop and cleaned up your do {} while() loop (which was being used incorrectly).
Here is the corrected method:
public static void ETA11_3()
{
int number = 0, total = 0, option = 0;
double counter = 0d;
while (true)
{
Console.WriteLine("Input a number (zero for stop): ");
number = Int16.Parse(Console.ReadLine());
total += number;
if (number == 0) break;
counter++;
}
Console.WriteLine("Choose an option: ");
Console.WriteLine("1 - Total");
Console.WriteLine("2 - Average");
option = Int16.Parse(Console.ReadLine());
switch (option)
{
case 1:
Console.WriteLine("Total: {0}", total);
break;
case 2:
Console.WriteLine("Total: {0}", total / counter);
break;
default:
Console.WriteLine("Invalid Option");
break;
}
}

Collecting multiple Variables from one loop

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.

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

Categories