C# Fast Food Menu - c#

I'm writing a program that displays a fast food menu and it allows the user to select an item. Then, the user enters the quantity of that item, and can continue selecting items with specific quantities until done. What I'm having trouble with is finding out how to calculate a running total. I am new to c# so I only know the basics. What is the best way to keep track of the running total while using multiple methods? In addition, I'm open to any criticism in my code. Thank you in advance.
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
bool ordering = true;
string userInput;
double itemPrice;
double itemQuantity;
double subTol;
string response;
void pricing()
{
Console.Write("Enter option 1, 2, 3: ");
userInput = Console.ReadLine();
switch (userInput)
{
case "1":
itemPrice = 3.00;
Console.WriteLine("You have picked a burger.");
break;
case "2":
itemPrice = 1.50;
Console.WriteLine("You have picked fries.");
break;
case "3":
itemPrice = 1.00;
Console.WriteLine("You have picked a soda.");
break;
default:
Console.WriteLine("That is not on our menu.");
pricing();
break;
}
}
void quantity()
{
Console.Write("Enter quantity: ");
itemQuantity = Convert.ToDouble(Console.ReadLine());
}
void subTotal()
{
subTol = itemQuantity * itemPrice;
Console.WriteLine();
Console.WriteLine("Your Subtotal: " + subTol);
}
while (ordering)
{
Console.WriteLine("What would you like from our menu?");
Console.WriteLine("\n1. Burger ($3.00) \n2. Fries ($1.50) \n3. Soda ($1.00)");
Console.WriteLine();
pricing();
quantity();
subTotal();
Console.Write("Would you like anything else? Y/N: ");
response = Console.ReadLine();
response = response.ToUpper();
if (response == "Y")
{
ordering = true;
}
else
{
ordering = false;
Console.WriteLine("Enjoy your meal!");
}
}
}
}
}

First of all, for the
If(response==“Y”)
Part you can actually just say
ordering = response == “Y”;
Also, this would only accept uppercase y. String.EqualsIgnoreCase() or something similar would probably do a better job
ordering = response.equalsIgnoreCase(“Y”);
You could keep a list of how many of each item the person has ordered, like
Int burgers = 0; and so on.
Then for the total, you could get 3*burgers + 1.5*fries and so on. However, if you want custom orders, using a struct might be better. For example, a struct could contain a type(burger or fries) and a price, depending on how many additions they have. You could also just add the price of each item to a total every time you order. This seems like a fun project, and I hope I could help!

For keeping track of total, the best approach would be to have a list of ordered items with their quantities, where you go and put each order from the user.
When you want to calculate the subtotal or total, you just go and compute from the list.
Here are some insights on how you can accomplish that, with some changes to the code you shared. Check the comments for details and reasoning.
namespace ConsoleApp1{
// creating record classes to store structured data
record MenuItem(string Product, decimal Price);
record Order(MenuItem Item, int Quantity);
class Program {
static void Main(string[] args) {
// better to keep your menu options & prices in a central place,
// instead of hardcoding them everywhere
List<MenuItem> menu = new() {
new ("Burger", 3.00M),
new ("Fries", 1.50M),
new ("Soda", 1.00M),
};
// this is a list to store the ordered items so far
List<Order> orders = new();
// moved most of the procedures to separate functions
do {
PrintMenu(menu);
var item = InputItem(menu);
var quantity = InputQuantity();
orders.Add(new Order(item, quantity));
PrintSubTotal(orders);
} while (CheckIfContinue());
PrintTotal(orders);
ByeBye();
}
static void PrintMenu(List<MenuItem> menu) {
// print each menu entry in a loop
Console.WriteLine("What would you like from our menu?");
for (int i = 0; i < menu.Count; i++) {
// adding 1 to the index for printing, because in c# indexes start at 0
Console.WriteLine($"{i + 1}: {menu[i].Product} (${menu[i].Price})");
}
Console.WriteLine();
}
static MenuItem InputItem(List<MenuItem> menu) {
// enter a loop, will be broken only if the input is correct
while (true) {
Console.Write($"Enter option: 1 to {menu.Count}: ");
if (int.TryParse(Console.ReadLine(), out int i) && i > 0 && i <= menu.Count) {
// must subtract 1 from the index, because indexes start from 0 in c#
Console.WriteLine($"You have picked {i}: {menu[i - 1].Product}.\n");
// if the input is a valid int
return menu[i - 1];
}
Console.WriteLine("That is not in our menu.\n");
}
}
static int InputQuantity() {
// same thing here, will repeat the loop unless the input is valid
while (true) {
Console.Write("Enter quantity: ");
if (int.TryParse(Console.ReadLine(), out int i) && i > 0) {
return i;
}
Console.WriteLine("Invalid quantity.\n");
}
}
static void PrintSubTotal(List<Order> orders) {
// using LINQ to iterate the list of orders sum up the prices x quantities
Console.WriteLine($"Your Subtotal: ${orders.Sum(o => o.Item.Price * o.Quantity)}\n");
}
static bool CheckIfContinue() {
Console.Write("Would you like anything else? Y/N: ");
// will return True if the input is y
return Console.ReadLine()?.Trim().ToUpper() == "Y";
}
static void PrintTotal(List<Order> orders) {
Console.WriteLine($"Your Order:");
foreach (var order in orders) {
// subtotal for each order item
Console.WriteLine($"{order.Item.Product, -10} x{order.Quantity, -4}: ${order.Item.Price * order.Quantity}");
}
// total for the whole order
Console.WriteLine($"---------- Total: ${orders.Sum(o => o.Item.Price * o.Quantity)}\n");
}
static void ByeBye() {
Console.WriteLine("Enjoy your meal!");
}
}
}

Related

c#. array keeps resetting itself in my switch

I'm currently in programming 101 and I've been stuck for a long time with an issue.
My assignment wants me to create a class with a bunch of methods to run with a switch case( as a menu).
If I press 1 (add passenger), it does what it's supposed to do the first time, but the second time, it just restarts the array.
I can't seem to save my answer to the array and then move on to the next spot in the array.
Would someone please explain how I'm supposed to "call" the array and save in it outside my for-loop in method add_pass?
using System;
namespace bussen
{
class buss
{
public int[] passagerare;
public int numbof_passagerare;
public void Run()
{
int nmr = 0;
do
{
Console.WriteLine("options:");
Console.WriteLine("1 add passenger");
Console.WriteLine("2 print out all passengers");
Console.WriteLine("3 calc average age");
Console.WriteLine("0 close program");
nmr = int.Parse(Console.ReadLine());
switch (nmr)
{
case 1:add_pass();
break;
case 2:all_pass();
break;
case 3:
break;
case 0:
break;
}
} while (nmr != 0);
}
public void add_pass()
{
if (passagerare.Length < 5)
{
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("type age of passenger");
int numbof_passenger = int.Parse(Console.ReadLine());
passagerare[i] = numbof_passenger;
break;
}
}
else if(passagerare.Length >= 5)
{
Console.WriteLine("buss is full");
}
}
public void all_pass()
{
foreach(int index in passagerare)
{
Console.WriteLine(index);
}
}
}
class Program
{
static void Main(string[] args)
{
var minbuss = new buss();
minbuss.Run();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
It's starting over because you're telling it to start over. The for loop starts at 0 every time.
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("type age of passenger");
int numbof_passenger = int.Parse(Console.ReadLine());
passagerare[i] = numbof_passenger;
break;
}
You need to find the length of the array and append the new entry. Try using a List instead of any array.
The issue was within the add_pass method, where i used a for - loop to add passengers. each time i pressed number 1 in the menu to call the method , the loop restarted the array wich i was saving the integers to.To get this right i just called the method without a loop like shown below. Thanks everybody for your help!
public void add_pass()
{
if (numbof_passagerare < 5)
{
Console.WriteLine("how old is the passenger");
int age = int.Parse(Console.ReadLine());
passagerare[numbof_passagerare++] = age;
}
else if(numbof_passagerare == 5)
{
Console.WriteLine("buss is full!");
}

What do I do/add to make the bus to stop taking in passengers at 25?

public void Run()
{
int menu = 0;
do
{
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("Welcome to the bus!");
Console.WriteLine("Choose and option:");
Console.WriteLine("1. Add passenger");
Console.WriteLine("2. Check the age of all the passengers on board");
Console.WriteLine("3. Calculate the total age of all the passengers on board");
Console.WriteLine("4. Exit the program!");
Console.WriteLine("-----------------------------------------------------");
menu = int.Parse(Console.ReadLine());
switch (menu)
{
case 1:
add_passenger();
break;
case 2:
print_buss();
break;
case 3:
total_age();
break;
}
} while (menu != 4);
}
public void add_passenger()
{
Console.WriteLine("How many passenger do you wanna add?");
int size = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < size; i++)
{
Console.WriteLine("Write the age of the passenger you wanna add: ");
int pass = Convert.ToInt32(Console.ReadLine());
passenger[i] = pass;
}
}
public void print_buss()
{
Console.WriteLine("The ages of the passengers on the bus are: ");
for (int i = 0; i < passenger.Length; i++)
{
Console.WriteLine(passenger[i] + "years old");
}
}
public int total_age()
{
int sum = 0;
for (int i = 0; i < passenger.Length; i++)
{
sum += passenger[i];
}
int total = sum;
Console.WriteLine("Total age of the passengers on board are " + total);
return total;
}
}
I have a little school project over the summer and this is a little part of code/program im doing and now im stuck. What do I do/add to make the bus to stop taking in passengers at 25? And have it written out that it is full? I have a array for 25, but I dont know what to do to make it stop taking in more people after 25? My head just stands still
Because your user can call your add_passenger routine multiple times, you need to keep track of how many passengers are on the bus already, and make your add_passenger method refuse to add more than the capacity of the passengers array, knowing how many are there already:
public void add_passenger()
{
Console.WriteLine("How many passenger do you wanna add?");
int size = Convert.ToInt32(Console.ReadLine());
//we could do something funky here like checking the request vs the bus size
if(size > passengers.Length - COUNT_OF_PASSENGERS_ALREADY_ON_THE_BUS)
{
//message the user to say that only passengers.Length - COUNT_OF_PASSENGERS_ALREADY_ON_THE_BUS will be added ...
}
for (int i = 0; i < size && COUNT_OF_PASSENGERS_ALREADY_ON_THE_BUS < passengers.Length; i++)
{
Console.WriteLine("Write the age of the passenger you wanna add: ");
int pass = Convert.ToInt32(Console.ReadLine());
passenger[COUNT_OF_PASSENGERS_ALREADY_ON_THE_BUS] = pass;
COUNT_OF_PASSENGERS_ALREADY_ON_THE_BUS++;
}
}
COUNT_OF_PASSENGERS_ALREADY_ON_THE_BUS is an integer, declared in the same place as the passengers array (and give it a nicer name than COUNT_OF_PASSENGERS_ALREADY_ON_THE_BUS - I only used all caps to make it clear the places in the code I used it)
You'll need to know how many passengers are on the bus so you can process other operations. It doesn't matter so much for the "add up the ages" thing because the slots you didn't use yet are pre filled with zeroes, so they wouldn't contribute to a sum, but if the task were switched to eg calculate the average age, then you'd have a problem
While I do not see where you created thepassenger array, I see that you have used it multiple times in your code. Also, you should convert it to a List to make it really work. So, you can simply add an if statement to your add_passenger method:
List<int> passenger = new List<int>();
public void add_passenger()
{
if(passenger.Length != 25){ //checking if the amount of passengers is not already equal to 25
Console.WriteLine("How many passenger do you wanna add?");
int size = Convert.ToInt32(Console.ReadLine());
if(passenger.Length+size < 26) //checking if the request does not exceed the passenger capacity
{
for (int i = 0; i < size; i++)
{
Console.WriteLine("Write the age of the passenger you wanna add: ");
int pass = Convert.ToInt32(Console.ReadLine());
passenger.Add(pass);
}
}
}
}

Why I can't able to get the User Input for The List Items through the Console Window?

I'm new to Programming. Now I have to learn C# List Items.
My Expectation:
Create an Empty List
Get the Input value for this list from the user through the console
Window.
My Program:
using System;
using System.Collections.Generic;
namespace Indexof_in_List
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Implementation of IndexOf Method with List");
Console.WriteLine();
//If the user entered empty value or nothing in the console window, the window will exit automatically
//Create an Empty List
List<int> name = new List<int>();
Console.WriteLine("Enter the Input values for the List");
//Get the Inputs for the List from the Console Window
for (int n = 0; n < name.Count; n++)
{
bool check;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name[n] = val;
}
else
{
Environment.Exit(0);
}
}
//Implement Index of any number in the list items which you have entered to the console
Console.WriteLine("The Index of value 10 is = {0}",name.IndexOf(10));
Console.WriteLine();
Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
Console.WriteLine();
Console.ReadKey();
}
}
}
Output:
Could Anyone Tell me the solution for this C# Logic? And also tell me the reason for this failure?
And Tell me, whether my Logic is correct or not?
Your code has a few issues:
Count retrieves the current number of items in your list.
You have created your list using the default constructor, so the Capacity is also 0. Because of this you can't loop from 0 to name.Capacity.
You are trying to add items using an index. You can only access existing items using the name[index] syntax.
The simplest solution is to initialize the list as you are, and simply add items:
List<int> name = new List<int>();
for (int i = 0; i < 10; ++i)
{
bool check;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name.Add(val);
}
else
{
Environment.Exit(0);
}
}
This will read 10 numbers one after the other and add them to the list.
Thank you for your valuable Comments. Finally, I have done the final changes based on your feedback.
My Code:
using System;
using System.Collections.Generic;
namespace Indexof_in_List
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Implementation of IndexOf Method with List");
Console.WriteLine();
//Create an Empty List
List<int> name = new List<int>();
//If the user entered empty value or nothing in the console window, the window will exit automatically
Console.WriteLine("Enter the Input values for the List");
//Get the Inputs for the List from the Console Window
for (int n=0;n<5;n++)
{
bool check=false;
string input = Console.ReadLine();
check = int.TryParse(input, out int val);
if (check)
{
name.Add(val) ;
}
else
{
Environment.Exit(0);
}
}
if (name.Count != 0)
{
//Implement Index of any number in the list items which you have entered to the console
int index1 = name.IndexOf(10);
Console.WriteLine("The Index of value 10 is = {0}", name.IndexOf(10));
if (index1!=-1)
{
Console.WriteLine("The number 10 found in the List");
}
else
{
Console.WriteLine("The Number 10 found in the List");
}
int index2 = name.IndexOf(1000);
Console.WriteLine("The Index of value 1000 is ={0}", name.IndexOf(1000));
if (index2 != -1)
{
Console.WriteLine("The number 1000 found in the List");
}
else
{
Console.WriteLine("The Number 1000 not found in the List");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}

Show two highest N numbers c#

I have a question, I want to know how i can show on CONSOLE the 2 highest of N entered numbers? Im doing something like this:
Console.WriteLine("Enter the weight of the fish:");
if(decimal.TryParse(Console.ReadLine(), out _fishWeight))
{
if (_fishWeight > _highest2)
{
_highest = _fishWeight;
if (_fishWeight < _highest1)
{
_highest = _fishWeight;
}
}
}
but it doesn't work. It only shows me the _highest1 but not the other _highest...
If someone can help me, I would be really glad!
you want something more like
if (_fishweight > _highest)
{
_highest2 = _highest;
_highest = _fishweight;
}
else if(_fishweight > _highest2)
{
_highest2 = _fishweight;
}
Alternatively If you want a more flexible leaderboard
// declare something like...
private List<int> _leaderboard = new List<int>();
private readonly int _leaderboardCount = 2;
// then update it like...
_leaderboard.Add(_fishweight);
_leaderboard = _leaderboard.OrderByDescending(v => v).Take(_leaderboardCount).ToList();
Now you have the top 2, but you can easily change it to a top 10 later on if you want.
Math.Max() is your friend here. No need to do manual comparison, just feed in two values, it'll output the highest of them and just set that to your _heighestWeight.
while (true)
{
Console.Write("Enter the weight of the fish: ");
var input = Console.ReadLine();
if (decimal.TryParse(input, out _fishWeight))
{
break;
}
Console.WriteLine("Please only enter a decimal number");
Console.Clear();
}
_heighestWeight = Math.Max(_fishWeight, _heighestWeight);
I also added a while loop in case they input something other than a decimal.

Confused about how to use return in c#

Ai'm new here and new in programming as well. I'm sorry if this question is really childish but i'm having some trouble using return type in a simple c# program.
Here is my code file, at d == 2 in AccountTest class, I want the withdrawal process to start over again but this time not asking the user to enter the account balance. A friend advice to use while loop but I have no idea how to use while loop over here. Thanks in advance. :)
using System;
public class Account
{
public static void Main(string[] args)
{
Console.Write("Enter your account balance: ");
int AccountBalance = Convert.ToInt32(Console.ReadLine());
Account.Debit(AccountBalance);
}
public static void Debit(int AccountBalance)
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
int WithdrawalAmount = Convert.ToInt32(Console.ReadLine());
AccountTest.DebitTest(AccountBalance, WithdrawalAmount);
}
}
And my Account class
public class AccountTest
{
public static int DebitTest(int AccountBalance, int WithdrawalAmount)
{
if (WithdrawalAmount > AccountBalance)
{
Console.WriteLine("\n\nDebit amount exceeded account balance.");
Console.ReadLine();
return 0;
}
else if (WithdrawalAmount <= 0)
{
Console.WriteLine("\n\nError. Incorrect amount.");
Console.ReadLine();
return 0;
}
else
{
int newBalance = AccountBalance - WithdrawalAmount;
Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
int InputNumber = Convert.ToInt32(Console.ReadLine());
if (InputNumber == 1)
{
Console.ReadLine();
return 0;
}
else if (InputNumber == 2)
{
return WithdrawalAmount;
}
else if (InputNumber == 3)
{
Console.WriteLine("\n\nYour remaining account balance is: {0}", newBalance);
Console.ReadLine();
return 0;
}
}
return 0;
}
}
Really the code should be refactored. Treating an Account like a thing makes more sense, in that it should be it's own object, and you should tell it what to do:
public class Account
{
public int Balance { get; set; }
public Account(int startBalance)
{
Balance = startBalance;
}
public void Debit(int amount) { Balance -= amount; }
public void Credit(int amount) { Balance += amount; }
}
Now, you can ask the user what they want to do with their Account, and you have room to add multiple accounts. So the program may look like:
int startingAmount = int.Parse(Console.ReadLine());
var account = new Account(startingAmount);
Console.WriteLine("1 to credit, 2 to debit, 0 to exit");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
//manipulate account
}
I'd start by reading up about static vs instance objects
first of, welcome to the coding community there is no childish question feel free to ask when ever you need, there some who will answer you with "google has the answer" but no worries a lot of other will help you, i saw you already selected an answer but ill add my point of view for you and the rest of new programmers.
a. if your new to codding never start with code it will only complicate things, instead start with a flow chart that illustrates what you to achieve from the program and from each component ( classes,functions etc. ) after you got that, its a lot easier to transform it to code, you can try using this site
it seems to be very user friendly and will draw you flow charts with the correct format.
b. like people here said before me never use variable like a,b,c because the next day youll try to continue where you left off and you will forget what you meant.
c. try to think of ways to use code to prevent repeating yourself.
d. using hard coded values is bad practice (hard coded means this:
return "this value to return is hard coded and will never change";
)
by the time i got to answer your question i already saw #Jonesy answer which is right and like what
i wanted to suggest so ill leave you with his answer.
hope this helps someone :)
The loop can be implemented in the Debit method:
public static void Debit(int AccountBalance)
{
int result = 0;
do
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
var WithdrawalAmount = Convert.ToInt32(Console.ReadLine());
result = AccountTest.DebitTest(AccountBalance, WithdrawalAmount);
} while (result != 0);
}
You should read up on while loops. Basically what you'd want is the method to return a number that decides what the program is supposed to do next, or when it should end. Think of the loop as your engine that states "As long as [chosen key] is not pressed, keep doing something".
A small example, with [chosen key] being 1, would be:
int choice = 0;
int balance = 100;
while (choice != 1) {
Console.WriteLine("Enter withdraw amount");
string userInput = Console.ReadLine();
// This will crash the program if the user enters text.
// Used for demonstration only. int.TryParse is preferred.
int value = int.Parse(userInput);
choice = AccountTest.DebitTest(balance, value);
}
class AccountTest {
public static int DebitTest(int AccountBalance, int WithdrawalAmount)
{
// do the test if the debit is OK
//..........
// At the end, you can do this. This till return the value entered and
// choice will be given a new value. If it was 1, the program will end.
// NOTE: It's not safe to use convert as
// it will crash the program if the user enters text.
return Convert.ToInt32(Console.ReadLine());
}
}
Note that this is not a functional ATM-program, as the balance never gets updated. I leave that for you to solve since I'm guessing this is for a class in programming =)
Well, this is my version of your program. I changed the behavior a bit (like asking again when the value is invalid). It's not perfect; for example, the messages and the RequestDebit method should be handled outside the Account class, perhaps in an AccountHandler class, but all this might be overkill for this simple exercise. Anyway I hope you find it useful:
public class Account
{
public int Balance { get; set; }
public Account(int startingBalance)
{
this.Balance = startingBalance;
}
private bool Debit(int amount)
{
if (amount <= 0)
{
Console.WriteLine("\n\nError. Incorrect amount.");
return false;
}
if (amount > this.Balance)
{
Console.WriteLine("\n\nDebit amount exceeded account balance.");
return false;
}
this.Balance -= amount;
Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.");
return true;
}
public void RequestDebit()
{
bool success;
do
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
int withdrawalAmount = Convert.ToInt32(Console.ReadLine());
success = this.Debit(withdrawalAmount);
} while (!success);
}
}
class Program
{
static void Main(string[] args)
{
int accountBalance;
do
{
Console.Write("Enter your account balance: ");
accountBalance = Convert.ToInt32(Console.ReadLine());
} while (accountBalance <= 0);
var myAccount = new Account(accountBalance);
myAccount.RequestDebit();
int inputNumber;
do
{
Console.WriteLine("\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
inputNumber = Convert.ToInt32(Console.ReadLine());
switch (inputNumber)
{
case 2: myAccount.RequestDebit();
break;
case 3:
Console.WriteLine("\n\nYour remaining account balance is: {0}", myAccount.Balance);
break;
}
} while (inputNumber != 1);
}
}

Categories

Resources