Enter a number or Q to quit - c#

Hi all I have been having some problems with a task I have been set
The first part of the task was to output a price table with the following rules:
The price for up to 50 is £5 each. For between 51 and 80, the price is £4 each, while for between 81 and 100 the price is a rock bottom £2.50 each.
Using loop structures and selection statements (if.. etc) your program should output a widget price chart for widgets in multiples of 10 up to 100.
I have done this however the second part of the task has me stumped
after the table has been output to input a number of widgets. You should then calculate the cost and output the value. If the user enters ‘q’ or ‘Q’, the program should terminate.
Here is the full code
using System;
namespace w5Task3
{
class Program
{ public static void Main ( string[] args )
{
double PriceEach1 = 5;
double PriceEach2 = 4;
double PriceEach3 = 2.50;
double Quantity = 10;
int UserOrder=0;
Console.WriteLine("\n\nBelow is the price chart:\n\n");
Console.WriteLine("WidgetQuantity\t\t\tPrice\n");
while (Quantity <=100)
{
double Price1 = PriceEach1*Quantity;
double Price2 = PriceEach2*Quantity;
double Price3 = PriceEach3*Quantity;
if (Quantity <=50)
{
Console.WriteLine("\t{0}\t\t\t{1:C}", Quantity, Price1);
}
if(Quantity >=51 && Quantity <=80)
{
Console.WriteLine("\t{0}\t\t\t{1:C}", Quantity, Price2);
}
if (Quantity >80 && Quantity <=100)
{
Console.WriteLine ("\t{0}\t\t\t{1:C}",Quantity, Price3);
}
Quantity +=10;
}
while (UserOrder >=0)
{
try
{
Console.WriteLine("Enter the amount of widgets you would like to purchase or press q to quit");
string temp = Console.ReadLine();
if (temp =="q") break;
if (temp =="Q") break;
int.TryParse(temp, out UserOrder);
double UserPrice;
if (UserOrder <=50)
{
UserPrice = UserOrder*5;
Console.WriteLine("The price is {0:C}",UserPrice);
}
if (UserOrder >=51 && UserOrder <=80)
{
UserPrice = UserOrder*4;
Console.WriteLine("The price is {0:C}",UserPrice");
}
if (UserOrder >80)
{
UserPrice = UserOrder*2.5;
Console.WriteLine("The price is {0:C}",UserPrice");
}
}
catch(Exception)
{
Console.WriteLine("You have entered an incorrect value. Please enter a number or press q to quit");
}
}
}
}
The part I am having issues with is:
while (UserOrder >=0)
{
try
{
Console.WriteLine("Enter the amount of widgets you would like to purchase or press q to quit");
string temp = Console.ReadLine();
if (temp =="q") break;
if (temp =="Q") break;
int.TryParse(temp, out UserOrder);
double UserPrice;
if (UserOrder <=50)
{
UserPrice = UserOrder*5;
Console.WriteLine("The price is {0:C}",UserPrice);
}
if (UserOrder >=51 && UserOrder <=80)
{
UserPrice = UserOrder*4;
Console.WriteLine("The price is {0:C}",UserPrice");
}
if (UserOrder >80)
{
UserPrice = UserOrder*2.5;
Console.WriteLine("The price is {0:C}",UserPrice");
}
}
catch(Exception)
{
Console.WriteLine("You have entered an incorrect value. Please enter a number or press q to quit");
}
}
}
I can get the program to quit or do one UserPrice but it is when I need to make it change the price dependent on the amount ordered.
Any help or suggestions are much appreciated!

You have newlines in your constant expressions at lines 67 and 73!
Fix those, and it all runs fine.

I think your problem is the quote after UserPrice on rows 64 and 70..
Console.WriteLine("The price is {0:C}",UserPrice");
remove it

The easiest way to do it is to adjust UserOrder after you calculate the price for that portion of the order. You can go in either direction, but it basically looks like:
if (HasThisQuantityRange)
{
Total += ThisAmount * (Lower of: ThisQuantity or UserOrder);
UserOrder -= (Lower of: ThisQuantity or UserOrder);
}
if (UserOrder > 0 && HasAdjustedQuantityRange)
{
Total += ThisAmount * (Lower of: ThisQuantity or UserOrder);
UserOrder -= (Lower of: ThisQuantity or UserOrder);
}
and so on.
Obviously, this is all pseudocode, and you'll need to implement it yourself, but this will hopefully get you pointed in the right direction.

I'm having trouble understanding what exactly the problem you're having is. Are you struggling to get the right calculation for the order or is the Quit behavior not acting in the way that you're expecting.
In general I think its bad form to use a transient variable like that for your while loop condition. When I want a console app to repeat I typically set up a variable specifically used for the loop condition like this:
bool isRunning = true;
while (isRunning)
{
....
Then when you check for your input
if (temp.ToUpper() == "Q")
{
isRunning = false;
break;
}

Related

I've made a code for a assignment but i need a push in the right direction [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 10 months ago.
Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
i need your guidance for this assignment:
At TEC Ballerup Stadium with room for 500 spectators, football matches are played every Sunday at 10.00. It is amateurs who play and it costs to watch the matches. There is access for adults and children, also spectators who are not members of the club (members of the club get a 10% discount!) A children's ticket costs DKK 30. An adult ticket costs DKK 65. Children only have access with an adult. first enter how many adult tickets and then how many children's tickets you want to buy. There must be a good guide so that the user of the program is not in doubt about what to enter.
a. Once the price has been calculated and displayed, the program must ask if you are a member of the club's association group. Here you can answer yes or no.
b. If you are a member, you get a discount of 10%. Print the discount.
c. There must be two loops (one for each entry of the number of tickets) so that you can order a maximum of 10 children's tickets and 10 adult tickets.
d. Make a printout that also tells how many tickets you have bought in total. So children and adult tickets together.
e. Some individual foreign spectators would like to pay in Euros. Modify the program so that it can also print the total price in EUR. Expect the course at the moment. is 757.34. Make sure to round to the whole Euro as we can not give back in foreign currency.
f. Add Date so that the application always prints the current date at the top right of the screen
So far i've coded this:
int maxNumber = 500;
int revenueSum = 0;
string adultBillet;
string childrenBillet;
int numberOrdered;
string numberOrderedString;
// How many adult tickets?
Console.WriteLine ("number of adult tickets");
Console.Write ("how many do you want?");
adultBillet = Console.ReadLine ();
// how many child tickets?
Console.WriteLine ("number of child tickets");
Console.Write ("how many do you want?");
childrenBillet = Console.ReadLine ();
String selection = "1";
while (choice! = "9")
{
Console.WriteLine ("How many adult tickets do you want ??");
numberOrdered = Convert.ToInt32 (Console.ReadLine ());
if (numberOrdered == 0)
{
Console.WriteLine ("You will need to purchase at least 1 ticket.");
}
else if (number Ordered> 10)
{
Console.WriteLine ("maximum number of adult tickets is 10.");
}
else if (numberOrdered> maxNumber)
{
Console.WriteLine ($ "Only {quantityOrder} left");
}
else
{
Console.WriteLine ($ "You have decided to purchase {number of Ordered} adult tickets");
}
Console.WriteLine ("are you a club member?");
Console.WriteLine ("please answer YES or NO");
String Club MemberReply = Console.ReadLine (). ToUpper ();
if (Club Member Answer == "YES")
{
Console.Write (numberOrdered * 65 * 0.9);
}
else if (Club MemberReply == "NO")
{
Console.Write(AmountofTickets * 65);
}
else
{
Console.WriteLine("Invalid answer");
i'm stuck on what to do now? It's all, all over the place, but uh I guess I need a loop for adulttickets and kidstickets and how many tickets in total and the euros and dkk's and finally the date
I made a demo for you according to your request, just for your reference.
You can use the following code to set a size for the console first.
Console.SetWindowSize(100, 50);
Console.SetBufferSize(100, 50);
Use this to output the date
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
Use int.TryParse to prevent users from entering incorrect information.
There are two main cycles, the purchase of adult tickets for the big cycle and the purchase of children's tickets for the small cycle.
The judgment condition is simpler. Entering the specified character is regarded as yes, otherwise it is regarded as no.
Below is my code:
using System;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
double adultPrice = 65, kidPrice = 30, totalPrices = 0;
int tmpTickets = 0, adultTickets = 0, kidsTickets = 0, totalTickets = 0, EurPrices = 0;
bool adultSuccess = false, kidSuccess = false;
Console.SetWindowSize(100, 50);
Console.SetBufferSize(100, 50);
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
Console.WriteLine("Welcome Ticket Mall!\n" +
"AdultPrice 65 DKK,childrenPrice 30 DKK.\n" +
"You can order a maximum of 10 children's tickets and 10 adult tickets.\n" +
"A child enters with an adult, so the child ticket cannot be larger than the adult ticket.");
while (!adultSuccess)
{
Console.WriteLine("Please enter the number of adult tickets.");
if (adultSuccess = int.TryParse(Console.ReadLine(), out tmpTickets))
{
if (tmpTickets < 0 || tmpTickets > 10)
{
Console.WriteLine("input error!please enter again!");
adultSuccess = false;
}
else if (tmpTickets == 0)
{
Console.WriteLine("Thanks for using, bye.");
}
else
{
adultTickets = tmpTickets;
Console.WriteLine("Do you need to buy a child ticket?\n" +
"Enter 'Y' or 'y' to go to the next step.");
string tmp = Console.ReadLine();
if (tmp != "Y" && tmp != "y")
{
break;
}
else
{
while (!kidSuccess)
{
Console.WriteLine("Please enter the number of kids tickets.");
if (kidSuccess = int.TryParse(Console.ReadLine(), out tmpTickets))
{
if (tmpTickets < 0 || tmpTickets > adultTickets)
{
Console.WriteLine("input error!please enter again!");
kidSuccess = false;
}
else
{
kidsTickets = tmpTickets;
}
}
}
}
}
}
}
Console.Clear();
Console.CursorLeft = Console.BufferWidth - 10;
Console.Write("{0}\n", DateTime.Now.ToString("yyyy-MM-dd"));
totalPrices = adultTickets * adultPrice + kidsTickets * kidPrice;
totalTickets = adultTickets + kidsTickets;
Console.WriteLine($"You have decided to purchase {adultTickets} adult tickets {kidsTickets} kid tickets\n" +
$"Total {totalTickets} tickets , {totalPrices} DKK ");
Console.WriteLine("are you a club member?\n" +
"Enter 'Y' or 'y' as a member.");
var tmp2 = Console.ReadLine();
if (tmp2 != "Y" && tmp2 != "y")
{
//1 Danish Krone is equal to 0.13 EUR now
EurPrices = Convert.ToInt32(totalPrices * 0.13);
Console.WriteLine($"You need to pay {totalPrices} DKK or {EurPrices} EUR! ");
}
else
{
totalPrices = totalPrices * 0.9;
EurPrices = Convert.ToInt32(totalPrices * 0.13);
Console.WriteLine($"As a member! You need to pay {totalPrices} DKK or {EurPrices} EUR !");
}
//Pause
Console.ReadLine();
}
}
}
Here is a screenshot of my demo:

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.

"Input string was not in a correct format" when trying to make a "menu" in windows console app

I wrote this code for class a few days ago. Everything looks correct, however, when I enter the input, I immediately get an error.
Any help on this would be greatly appreciated.
Console.WriteLine("The following are the benefit packages: ");
Console.WriteLine("Employee only (E) ");
Console.WriteLine("Employee and spouse (S) ");
Console.WriteLine("Employee and children (C) ");
Console.WriteLine("Employee and family (F) ");
Console.WriteLine();
Console.WriteLine("Please select your benefit type for medical insurance: ");
string medical = Console.ReadLine();
double subtotal = Convert.ToDouble(Console.ReadLine());
///the error is with the double above. I'm not sure how to work around this.
if (medical == "e")
{
subtotal += 0;
}else if (medical == "s")
{
subtotal += 50;
}else if (medical == "c")
{
subtotal += 100;
}else if (medical == "f")
{
subtotal += 200;
}
Console.WriteLine("Please select your benefit type for dental insurance: ");
string dental = Console.ReadLine();
if (dental == "e")
{
subtotal += 50;
}else if (dental == "s")
{
subtotal += 125;
}else if (dental == "c")
{
subtotal += 225;
}else if (dental == "f")
{
subtotal += 325;
}
Console.WriteLine("Please select your benefit type for vision insurance: ");
string vision = Console.ReadLine();
if (vision == "e")
{
subtotal += 25;
}else if (vision == "s")
{
subtotal += 60;
}else if (vision == "c")
{
subtotal += 110;
}else if (vision == "f")
{
subtotal += 185;
}
Console.WriteLine("Please enter your years in service: ");
int years = Convert.ToInt16(Console.ReadLine());
double discount = Convert.ToDouble(Console.ReadLine());
if (years >= 20)
{
discount = .2;
}else if (years >= 10 && years < 20)
{
discount = .1;
}else if (years < 10)
{
discount = 0;
}
double total = subtotal + (subtotal * discount);
Console.WriteLine("Your total out-of-pocket premium: " + total);
Console.ReadLine();
Each time the user "selects" a package, the value of the "subtotal" will increase. Later, the final total is calculated for, giving the user a final cost of these premiums.
string medical = Console.ReadLine();
double subtotal = Convert.ToDouble(Console.ReadLine());
this is asking for two inputs, the first Console.ReadLine(); sets your string medical. this is good.
lets say i enter E
now medical = "E"
now before it gets to your loop to determine what to do with "E", your asking for another input, and trying to convert it to a double. i would change the second line:
double subtotal = Convert.ToDouble(Console.ReadLine());
to
double subtotal = 0.0;
this will give you an starting value. if you know the "procedure cost" which i assume is your double, you can set it to whatever you want, but if you want to ask for the value use:
double subtotal = double.Parse(System.Console.ReadLine());
also the way your options are set up....
Console.WriteLine("Employee only (E) ");
Console.WriteLine("Employee and spouse (S) ");
Console.WriteLine("Employee and children (C) ");
Console.WriteLine("Employee and family (F) ");
is going to encourage people to enter capital letters. this is fine, but you're only checking for lower case, i suggest:
if (vision == "e"||vision == "E")
EDIT: i forgot to tell you, when working with dollar amounts, its best to use decimal not double.

C# do while loops - How to remember user input?

I'm new to C#, and i'm writing a do while loop that continues to ask the user to enter "price", until they enter "-1" for price.
Afterwards, I need to add up all the values for price they entered and declare that as the subtotal.
The problem I have is that it only remember the last number entered, which would be -1. What would I have to do to fix this?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
} while (price != -1);
subtotal = Convert.ToInt32(price);
Console.Write("Subtotal: ${0}", subtotal);
}
}
}
Try this variation to Artem's answer. I think this is a little cleaner.
int count = 0;
decimal input = 0;
decimal price = 0;
while (true)
{
Console.Write("Item {0} Enter Price: ", count++);
input = Convert.ToDecimal(Console.ReadLine());
if (input == -1)
{
break;
}
price += input;
}
In each iteration of the loop, you overwrite the value of price. Separate input and storage price.
decimal input = 0;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
input = Convert.ToDecimal(Console.ReadLine());
if (input != -1)
price += input;
} while (input != -1);
Use a list and keep adding the entries to the list.
Or you can keep a running total in another integer.
Something like:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;
Please try to use this
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal = 0m; //subtotal is needed to be initialized from 0
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
if (price != -1) //if the console input -1 then we dont want to make addition
subtotal += price;
} while (price != -1);
//subtotal = Convert.ToInt32(price); this line is needed to be deleted. Sorry I didnt see that.
Console.Write("Subtotal: ${0}", subtotal); //now subtotal will print running total
}
}
}

No overload method 'conversationOutput' takes '2' arguments

Hi I'm having trouble with an error "No overload method 'conversationOutput' takes '2' arguments" please help. I'm having a little trouble understanding method calling, and calling variables from main().
class MainClass
{
static void Main ()
{
string selection;
double values;
selection = userChoice();
values = userInput(selection);
conversationOutput(selection, values);
}
static string userChoice ()
{
string choose;
Console.WriteLine("Welcome to the OHM's law calculator! \n \nWhat would you like to calcualte?");
Console.WriteLine("1. Voltage:");
Console.WriteLine("2. Current:");
Console.WriteLine("3. Resistance:");
do
{
choose = Console.ReadLine();
if (choose != "1" && choose != "2" && choose != "3")
{
Console.WriteLine("Please only select '1' for voltage, '2' for current, '3' resistance");
}
} while (choose != "1" && choose != "2" && choose != "3");
switch (choose)
{
case "1":
Console.Write("You have choose to calculate Voltage.\n");
break;
case "2":
Console.Write("You have choose to calculate Current.\n");
break;
case "3":
Console.WriteLine("You have choose to calculate Resistance.\n");
break;
}
return choose;
}
static double userInput (string choose)
{
double voltageD = 0.0;
double currentD = 0.0;
double resistanceD = 0.0;
string current;
string voltage;
string resistance;
bool ok = true;
do if (choose != "1")
{
do
{
Console.WriteLine("Please enter your value for Voltage (volts)...");
voltage = Console.ReadLine();
ok = double.TryParse(voltage, out voltageD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (voltageD < 0)
{
Console.WriteLine("Please select a number larger than the lower limit of 0 volts");
}
} while (voltageD < 0);
do if (choose != "2")
{
do
{
Console.WriteLine("Please enter your value for Current (amp)...");
current = Console.ReadLine();
ok = double.TryParse(current, out currentD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (currentD < 0.01)
{
Console.WriteLine("Please select a number larger than the lower limit of 0.01 amp");
}
} while (currentD < 0.01);
do if (choose != "3")
{
do
{
Console.WriteLine("Please enter your value for Resistance (ohm)...");
resistance = Console.ReadLine();
ok = double.TryParse(resistance, out resistanceD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (resistanceD < 10)
{
Console.WriteLine("Please select a number larger than the lower limit of 10 ohm");
}
} while (resistanceD < 10);
return 0;
}
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
{
/* v = i*r */
double output = 0.0;
string units = "";
if (choose == "1")
{
output = (currentD) * (resistanceD);
units = "Volts";
}
if (choose == "2")
{
output = (voltageD) / (resistanceD);
units = "Amps";
}
if (choose == "3")
{
output = (voltageD) / (resistanceD);
units = "OHM";
}
Console.WriteLine("The calculated value is {0:F3} {1:F3}", output, units);
return 0;
}
}
The reason is you have a method
double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
which has 4 parameters and you are passing only 2 parameters to the method.
define the missing parameters as optional
static double conversationOutput (string choose, double currentD, double voltageD =0, double resistanceD =1)
As per the method definition, conversationOutput expects four parameters.
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD) {}
But you are calling it by passing just two parameters.
conversationOutput(selection, values);
That's why you are getting such error.
It will work if you call the conversationOutput method by passing four parameters.

Categories