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.
Related
I am currently making a lottery simulator in C# but now that I wanted to make a feature to let the User randomize their lottery numbers instead of having to write them manually using arrays, but it gives me the Error Code:
Exception thrown
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I declared and initialized my array named "randomList" for the random numbers like this:
public static int[] randomList = new int[5];
After I wanted to write the code that stores the 6 random numbers the user got in the array:
Console.WriteLine("\nRandomized 6 numbers: ");
for (int z = 0; z <= 6; z++)
{
int rndNum = rnd.Next(1, 50);
randomList[z] = rndNum; // <-- ERROR
Console.Write(rndNum + ", ");
}
I thought that you would only get that Error if you haven't initialized your variable or array. I would love someone explain the error to me and how to avoid/fix it! Thanks!
Here you can access the entire code (Error in line 203):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Lottery
{
internal class Program
{
// Global Variables:
// Playing
public static int playoption;
public static int betoption;
public static int gameAmount;
public static int gameCost = 10;
public static int superNumCost = 5;
public static string includeSuperNum;
public static int tickets;
public static int superNumTickets;
// Used for the Lotto Numbers
public static int[] correctList = new int[5];
public static int[] randomList = new int[5];
public static int[] manualList = new int[5];
// Indicators if you have correct numbers
public static int userCorrect;
public static int userSuperCorrect;
// Bank
public static int bankoption;
public static int deposit;
public static int withdrawal;
public static int balance = 0;
public static int cash = 300;
static void Main()
{
// Variables
// Menu
int menuoption;
Console.Clear();
Console.WriteLine("=== LOTTO! 6 out of 49 ===");
Console.WriteLine(" 1. Play");
Console.WriteLine(" 2. Bank Menu");
Console.WriteLine(" 3. Go work");
Console.WriteLine(" 4. Quit");
WrongMenu:
Console.Write("\nEnter your option by typing out the number: ");
menuoption = Convert.ToInt32(Console.ReadLine());
switch (menuoption)
{
case 1:
PlayMenu();
break;
case 2:
Bank();
break;
case 3:
Work();
break;
case 4:
break;
default:
Console.WriteLine("Invalid option - Enter your option again: ");
goto WrongMenu;
}
}
// All code for playing Lotto:
static void PlayMenu()
{
Console.Clear();
Console.WriteLine("=== PLAY MENU ===");
Console.WriteLine(" 1. Buy Tickets");
Console.WriteLine(" 2. Check Tickets");
Console.WriteLine(" 3. Back to Main Menu");
WrongPlayMenu:
Console.Write("\nEnter your option to continue: ");
playoption = Convert.ToInt32(Console.ReadLine());
switch (playoption)
{
case 1:
Console.Clear();
Console.WriteLine("=== PRIZES ===");
Console.WriteLine(" Lottery ticket = " + gameCost + " Euro");
Console.WriteLine(" Super Number Addon = " + superNumCost + " Euro");
Console.Write("\nHow many lottery tickets do you want to buy?: ");
gameAmount = Convert.ToInt32(Console.ReadLine());
if ((gameCost * gameAmount) <= cash)
{
cash = cash - (gameCost * gameAmount);
Console.WriteLine("Successfully bought " + gameAmount + " lottery tickets!");
if (cash - (gameAmount * superNumCost) >= 0)
{
Console.Write("\nDo you want to buy the Super Number Addon to maximize your potencial winnings? (Y/N): ");
includeSuperNum = Console.ReadLine();
while (includeSuperNum != "Y" && includeSuperNum != "N")
{
Console.WriteLine("Invalid answer - Type in your answer again only using Y for Yes or N for No.");
Console.Write("\nDo you want to buy the Super Number Addon to maximize your potencial winnings? (Y/N): ");
includeSuperNum = Console.ReadLine();
}
if (includeSuperNum == "Y")
{
cash = cash - (gameAmount * superNumCost);
superNumTickets += gameAmount;
Console.WriteLine("Successfully bought Super Number Addon for your ticket/s!");
}
else
{
tickets = tickets + gameAmount;
Console.WriteLine("No Super Number Tickets bought - Transaction done");
}
}
}
Console.WriteLine("\nPress any key to go back to Play Menu");
Console.ReadKey();
PlayMenu();
break;
case 2:
Console.Clear();
if (tickets == 0 && superNumTickets == 0)
{
Console.WriteLine("You have no tickets - Go buy some!");
Console.WriteLine("Press any key to go back to Play Menu");
Console.ReadKey();
PlayMenu();
}
if (tickets >= 1)
{
Console.WriteLine("\nYou have " + tickets + " normal tickets");
}
if (superNumTickets >= 1)
{
Console.WriteLine("You have " + superNumTickets + " tickets with the Super Number Addon.\n");
}
Console.WriteLine("=== BETTING ON TICKETS ===");
Console.WriteLine(" 1. Bet on normal tickets");
Console.WriteLine(" 2. Bet on Super Number tickets");
Console.WriteLine(" 3. Back to Play Menu");
BetWrong:
Console.Write("\nEnter your option by typing out the number: ");
betoption = Convert.ToInt32(Console.ReadLine());
switch (betoption)
{
case 1:
Bet();
break;
case 2:
SuperBet();
break;
case 3:
PlayMenu();
break;
default:
Console.WriteLine("Invalid answer - Try typing it again.");
goto BetWrong;
}
break;
case 3:
Main();
break;
default:
Console.WriteLine("Invalid answer - Try typing it again.");
goto WrongPlayMenu;
}
}
static void Bet()
{
Console.WriteLine("Your tickets:\n");
for (int x = 1; x <= tickets; x++)
{
Console.WriteLine(" Normal ticket Nr. " + x);
}
Console.Write("\nEnter the ticket number to bet on it: ");
int ticketNum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nSuccessfully opened ticket Nr. " + ticketNum);
WrongRandomOption:
Console.Write("Do you want to randomize your 6 Numbers or write them out? Enter 1 for random or 2 for manual: ");
int chooseIfRandom = Convert.ToInt32(Console.ReadLine());
Random rnd = new Random();
switch (chooseIfRandom)
{
case 1:
Console.WriteLine("\nRandomized 6 numbers: ");
for (int z = 0; z <= 5; z++)
{
int rndNum = rnd.Next(1, 50);
randomList[z] = rndNum;
Console.Write(rndNum + ", ");
}
Console.WriteLine("\nThe correct Numbers are: ");
for (int c = 1; c <= 5; c++)
{
int correctNum = rnd.Next(1, 50);
correctList[c] = correctNum;
Console.Write(correctNum + ", ");
}
for (int h = 0; h <= 6; h++)
{
if (randomList[h] == correctList[h])
{
userCorrect++;
}
}
Console.WriteLine("You got " + userCorrect + " correct Numbers");
switch (userCorrect)
{
case 1:
Console.WriteLine("You won 3 Euros!");
cash += 3;
break;
case 2:
Console.WriteLine("Nice! You won 7 Euros!");
cash += 7;
break;
case 3:
Console.WriteLine("Wow! You won 12 Euros!");
cash += 12;
break;
case 4:
Console.WriteLine("Amazing! You won 50 Euros!");
cash += 50;
break;
case 5:
Console.WriteLine("Incredible! You won 4.200 Euros!");
cash += 4200;
break;
case 6:
Console.WriteLine("JACKPOT! You won 830.000 Euros!");
cash += 830000;
break;
}
userCorrect = 0;
break;
case 2:
for (int m = 0; m <= 6; m++)
{
ManualWrong:
Console.WriteLine("Enter your " + (m + 1) + ". number: ");
manualList[m] = Convert.ToInt32(Console.ReadLine());
if (manualList[m] >= 50 || manualList[m] < 1)
{
Console.WriteLine("Entered number is either too high or low - Enter again (Between 1 and 49)\n");
goto ManualWrong;
}
}
Console.WriteLine("\nYour numbers are: ");
for (int k = 0; k <= 6; k++)
{
Console.Write(manualList[k] + ", ");
}
Console.WriteLine("\nThe correct Numbers are: ");
for (int l = 1; l <= 6; l++)
{
int correctNum = rnd.Next(1, 50);
correctList[l] = correctNum;
Console.Write(correctNum + ", ");
}
for (int m = 0; m <= 6; m++)
{
if (manualList[m] == correctList[m])
{
userCorrect++;
}
}
Console.WriteLine("You got " + userCorrect + " correct Numbers");
switch (userCorrect)
{
case 1:
Console.WriteLine("You won 3 Euros!");
cash += 3;
break;
case 2:
Console.WriteLine("Nice! You won 7 Euros!");
cash += 7;
break;
case 3:
Console.WriteLine("Wow! You won 12 Euros!");
cash += 12;
break;
case 4:
Console.WriteLine("Amazing! You won 50 Euros!");
cash += 50;
break;
case 5:
Console.WriteLine("Incredible! You won 4.200 Euros!");
cash += 4200;
break;
case 6:
Console.WriteLine("JACKPOT! You won 830.000 Euros!");
cash += 830000;
break;
}
break;
default:
Console.WriteLine("Invalid answer - Only answer 1 or 2!");
goto WrongRandomOption;
}
Console.WriteLine("Press any key to go back to Play Menu.");
Console.ReadKey();
PlayMenu();
}
static void SuperBet()
{
Console.WriteLine("Your Super Number tickets:\n");
for (int y = 1; y <= superNumTickets; y++)
{
Console.WriteLine(" Super Number ticket Nr. " + y);
}
Console.Write("\nEnter the ticket number to bet on it: ");
int superTicketNum = Convert.ToInt32(Console.ReadLine());
}
// The Bank Menu
static void Bank()
{
Console.Clear();
Console.WriteLine("=== BANK MENU ===");
Console.WriteLine(" 1. Check balance");
Console.WriteLine(" 2. Deposit");
Console.WriteLine(" 3. Withdraw");
Console.WriteLine(" 4. Invest (Coming Soon)");
Console.WriteLine(" 5. Back to Main Menu");
WrongBankMenu:
Console.Write("\nEnter your option by typing out the number: ");
bankoption = Convert.ToInt32(Console.ReadLine());
switch (bankoption)
{
case 1:
Console.WriteLine("\nYour current bank balance is: " + balance + " Euros.");
Console.WriteLine("Your current balance of cash is: " + cash + " Euros.");
Console.WriteLine("\nPress any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 2:
NotEnoughCash:
Console.Write("Deposit amount: ");
deposit = Convert.ToInt32(Console.ReadLine());
if (deposit <= cash)
{
balance += deposit;
cash -= deposit;
Console.WriteLine("Successfully deposited " + deposit + " Euros!");
}
else
{
Console.WriteLine("You dont have enough to deposit this amount.");
Console.WriteLine("Your current maximum deposit amount is: " + cash + " Euros.\n");
goto NotEnoughCash;
}
Console.WriteLine("Press any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 3:
NotEnoughBalance:
Console.Write("Withdraw amount: ");
withdrawal = Convert.ToInt32(Console.ReadLine());
if (withdrawal <= balance)
{
balance -= withdrawal;
cash += withdrawal;
Console.WriteLine("Successfully withdrawn " + withdrawal + " Euros.");
}
else
{
Console.WriteLine("Your balance is smaller than your withdraw amount!");
Console.WriteLine("Your current maximum withdraw amount is: " + balance + " Euros.\n");
goto NotEnoughBalance;
}
Console.WriteLine("Press any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 4:
Console.WriteLine("This feature is coming soon!\n");
Console.WriteLine("Press any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 5:
Main();
break;
default:
Console.WriteLine("Invalid option - Enter your option again: ");
goto WrongBankMenu;
}
}
// All Code for working:
static void Work()
{
}
}
}
Here is my vending machine. I now need to be able to be able to repeat the menu at the end of the switch to allow the user to go back into the vending machine or exit the program.
Would I use a while loop or an if/else statement. I tried nesting the whole thing in a while loop but then it repeated the the purchase option.
int iNumCrisps = 10;
int iCrispsBought;
int iNumChocbars = 20;
int iChocbarsBought;
int iNumSweets = 30;
int iSweetsBought;
double dTotalMoney = 0;
int iChoice;
{
//display the choices
Console.WriteLine("Vending Machine");
Console.WriteLine("1 - Buy chocbars");
Console.WriteLine("2 - Buy crisps");
Console.WriteLine("3 - Buy sweets");
// get the users choice
Console.Write("Enter your choice: ");
iChoice = Convert.ToInt32(Console.ReadLine());
//validate user input
while (iChoice < 1 || iChoice > 3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
iChoice = Convert.ToInt32(Console.ReadLine());
}
switch (iChoice)
{
case 1: //user has chosen chocbars
Console.WriteLine();
Console.Write("How many chocbars do you wish to purchase?");
iChocbarsBought = Convert.ToInt32(Console.ReadLine());
iNumChocbars = iNumChocbars - iChocbarsBought;
dTotalMoney = dTotalMoney + (iChocbarsBought * 0.25);
Console.WriteLine("There are now" + iNumChocbars + " chocbars in the machine");
break;
case 2: //User has chosen crisps
Console.WriteLine();
Console.Write("How many crisps do you wish to purchase?");
iCrispsBought = Convert.ToInt32(Console.ReadLine());
iNumCrisps = iNumCrisps - iCrispsBought;
dTotalMoney = dTotalMoney + (iCrispsBought * 0.30);
Console.WriteLine("There are now" + iNumCrisps + " crisps in the machine");
break;
case 3: //user has chosen sweets
Console.WriteLine();
Console.Write("How many sweets do you wish to purchase?");
iSweetsBought = Convert.ToInt32(Console.ReadLine());
iNumSweets = iNumSweets - iSweetsBought;
dTotalMoney = dTotalMoney + (iSweetsBought * 0.20);
Console.WriteLine("There are now " + iNumSweets + " sweets in the machine");
break;
default:
Console.WriteLine("You must enter a number from 1 to 3");
break;
}// end switch
//validate user input
while (iChoice < 1 || iChoice > 3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
iChoice = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("There is now" + dTotalMoney + "p in the machine");
Console.WriteLine();
Console.WriteLine("Press any key to close");
Console.WriteLine();
Console.ReadKey();
}
}
}
}
I guess you are quite new to programming.
What you need to do is place the menu in a function. This is a block of code that you can call from elsewhere in the code. I'm guessing this code comes from the main function?
private static int ShowMenu ()
{
int iChoice = 0;
//display the choices
Console.WriteLine("Vending Machine");
Console.WriteLine("1 - Buy chocbars");
Console.WriteLine("2 - Buy crisps");
Console.WriteLine("3 - Buy sweets");
// get the users choice
Console.Write("Enter your choice: ");
iChoice = Convert.ToInt32(Console.ReadLine());
return iChoice;
}
You would then use this line to show the menu and get the choice
iChoice = ShowMenu();
You could then look at checking that the user's input was a valid number and things like that as part of this function
I'm creating a simple calculator for my C# class and having some trouble with the final calculations.
I've declared my variables and I'm using simple if then statements for the order. My problem is, after I've defined my variables, the information they contain doesn't change when the calculation is performed, they simply just output zero as defined by the original value instead of outputting the new amount from the if statement (TotalCost, Tax, TotalWithTax).
I've input different numbers in place of the zero and the formulas work, it's just that the value never changes to what I have stated in the
If statements. Is it not possible to adjust the value of a variable from within a if statement?
What is another possible way to go about this if that is the case?
Trying to keep it simple as I'm not really proficient with console programming.
string SizeName = "";
double SizeCost = 0;
string ToppingName = "";
double ToppingCost = 0;
double TotalCost = (SizeCost + ToppingCost);
double Tax = (TotalCost*0.085);
double TotalWithTax = (TotalCost + Tax);
//Print a greeting message.
Console.WriteLine("Welcome to the Central Pizza Parlor!");
//Ask if the customer would like to order a pizza.
Console.WriteLine("Would you like to order a pizza today? Enter y for Yes or n for No.");
string Order = Console.ReadLine();
//Start the order if answer is Yes, if not, then exit the program.
if (Order == "y")
{
//Continue with order.
Console.WriteLine("Great! Let's get started, please pick the size of your pizza:");
Console.WriteLine("1 - Small $5.00");
Console.WriteLine("2 - Medium $7.00");
Console.WriteLine("3 - Large $9.00");
//Get pizza size for order.
Console.WriteLine("Please enter the number for the pizza size you would like.");
string sizeAsAString = Console.ReadLine();
int size = Convert.ToInt32(sizeAsAString);
//Use If Else statement to set the variable value for SizeCost.
if (size == 1)
{
SizeCost = 5.0;
SizeName = ("Small");
}
else if (size == 2)
{
SizeCost = 7.0;
SizeName = ("Medium");
}
else if (size == 3)
{
SizeCost = 9.0;
SizeName = ("Large");
}
//Have Customer select toppings.
Console.WriteLine("Please select which topping you would like on your pizza.");
;
Console.WriteLine("1 - Pepperoni $2.00");
Console.WriteLine("2 - Ham $2.00");
Console.WriteLine("3 - Onions $1.00");
Console.WriteLine("4 - Mushrooms $1.00");
Console.WriteLine("5 - Green Peppers $1.00");
Console.WriteLine("Please enter the number for the corresponding topping you would like.");
string toppingAsAString = Console.ReadLine();
int topping = Convert.ToInt32(toppingAsAString);
//Use If Else statement to set the variable value for ToppingCost.
if (topping == 1)
{
ToppingCost = 2.0;
ToppingName = ("Pepperoni");
}
else if (topping == 2)
{
ToppingCost = 2.0;
ToppingName = ("Ham");
}
else if (topping == 3)
{
ToppingCost = 1.0;
ToppingName = ("Onions");
}
else if (topping == 4)
{
ToppingCost = 1.0;
ToppingName = ("Mushrooms");
}
else if (topping == 5)
{
ToppingCost = 1.0;
ToppingName = "Green Peppers";
}
//Display order details.
Console.WriteLine("Here are the details for your order.");
Console.WriteLine("Thank you for your business!");
Console.WriteLine("You can pick up your pizza in 25 minutes!");
//Show current time of order.
DateTime now = DateTime.Now;
Console.WriteLine("Time Ordered: "+now+" ");
//Show Current time of order with additional 25 minutes for pickup.
DateTime pickup = DateTime.Now.AddMinutes(25);
Console.WriteLine("Pick Up At: "+pickup+" ");
//Output Pizza Size.
Console.WriteLine("Size: " +SizeName+ " ");
//OutPut Topping name.
Console.WriteLine("Topping: " +ToppingName+ " ");
Console.WriteLine("---------------");
//Output total price of size and topping chosen.
Console.WriteLine("Pizza Price: $ "+TotalCost+" ");
//Output tax amount.
Console.WriteLine("Tax: $" +Tax+ " ");
//Output total price with tax.
Console.WriteLine("Total Price: $" +TotalWithTax+ " ");
}
else
{
//Exit the program because the customer does not want to order a pizza.
Console.WriteLine("Alright, have a great day!");
}
Console.ReadLine();
}
}
}
All your calcualtions are at the top(in declaration). Performing your calculations with defaults will not output desired result.
double TotalCost = (SizeCost + ToppingCost);
double Tax = (TotalCost*0.085);
double TotalWithTax = (TotalCost + Tax);
Move these calcualtions to bottom (before outputting).
public class Program
{
public static void Main()
{
string SizeName = "";
double SizeCost = 0;
string ToppingName = "";
double ToppingCost = 0;
double TotalCost =0;
double Tax = 0;
double TotalWithTax = 0;
//Print a greeting message.
Console.WriteLine("Welcome to the Central Pizza Parlor!");
//Ask if the customer would like to order a pizza.
Console.WriteLine("Would you like to order a pizza today? Enter y for Yes or n for No.");
string Order = Console.ReadLine();
//Start the order if answer is Yes, if not, then exit the program.
if (Order == "y")
{
//Continue with order.
Console.WriteLine("Great! Let's get started, please pick the size of your pizza:");
Console.WriteLine("1 - Small $5.00");
Console.WriteLine("2 - Medium $7.00");
Console.WriteLine("3 - Large $9.00");
//Get pizza size for order.
Console.WriteLine("Please enter the number for the pizza size you would like.");
string sizeAsAString = Console.ReadLine();
int size = Convert.ToInt32(sizeAsAString);
//Use If Else statement to set the variable value for SizeCost.
if (size == 1)
{
SizeCost = 5.0;
SizeName = ("Small");
}
else if (size == 2)
{
SizeCost = 7.0;
SizeName = ("Medium");
}
else if (size == 3)
{
SizeCost = 9.0;
SizeName = ("Large");
}
//Have Customer select toppings.
Console.WriteLine("Please select which topping you would like on your pizza.");
;
Console.WriteLine("1 - Pepperoni $2.00");
Console.WriteLine("2 - Ham $2.00");
Console.WriteLine("3 - Onions $1.00");
Console.WriteLine("4 - Mushrooms $1.00");
Console.WriteLine("5 - Green Peppers $1.00");
Console.WriteLine("Please enter the number for the corresponding topping you would like.");
string toppingAsAString = Console.ReadLine();
int topping = Convert.ToInt32(toppingAsAString);
//Use If Else statement to set the variable value for ToppingCost.
if (topping == 1)
{
ToppingCost = 2.0;
ToppingName = ("Pepperoni");
}
else if (topping == 2)
{
ToppingCost = 2.0;
ToppingName = ("Ham");
}
else if (topping == 3)
{
ToppingCost = 1.0;
ToppingName = ("Onions");
}
else if (topping == 4)
{
ToppingCost = 1.0;
ToppingName = ("Mushrooms");
}
else if (topping == 5)
{
ToppingCost = 1.0;
ToppingName = "Green Peppers";
}
TotalCost = (SizeCost + ToppingCost);
Tax = (TotalCost*0.085);
TotalWithTax = (TotalCost + Tax);
//Display order details.
Console.WriteLine("Here are the details for your order.");
Console.WriteLine("Thank you for your business!");
Console.WriteLine("You can pick up your pizza in 25 minutes!");
//Show current time of order.
DateTime now = DateTime.Now;
Console.WriteLine("Time Ordered: "+now+" ");
//Show Current time of order with additional 25 minutes for pickup.
DateTime pickup = DateTime.Now.AddMinutes(25);
Console.WriteLine("Pick Up At: "+pickup+" ");
//Output Pizza Size.
Console.WriteLine("Size: " +SizeName+ " ");
//OutPut Topping name.
Console.WriteLine("Topping: " +ToppingName+ " ");
Console.WriteLine("---------------");
//Output total price of size and topping chosen.
Console.WriteLine("Pizza Price: $ "+TotalCost+" ");
//Output tax amount.
Console.WriteLine("Tax: $" +Tax+ " ");
//Output total price with tax.
Console.WriteLine("Total Price: $" +TotalWithTax+ " ");
}
else
{
//Exit the program because the customer does not want to order a pizza.
Console.WriteLine("Alright, have a great day!");
}
Console.ReadLine();
}
}
Fiddler Demo
You set TotalCost before changing the Values of SizeCost or ToppingCost.
Move these lines
double TotalCost = (SizeCost + ToppingCost);
double Tax = (TotalCost*0.085);
double TotalWithTax = (TotalCost + Tax);
to after your input section.
The following is the definition on which I am working on it. But I am not able to go further. Switch statement is not working and directly shows the default msg.
Can anybody help me with this ?
Allow the user to choose one of three boxes of fruit (apples, bananas, or cherries) and then ask the quantity of fruit boxes (5, 10, or 15). The cost of each fruit box is as follows: Apples - $0.25, Bananas - $1.60, and Cherries - $2.50. The quantity of fruit boxes should only be requested from the user if a valid fruit box was selected. Otherwise display an error message and exit application. After the type of fruit and quantity is selected display the total price (fruit box price times box quantity). If the user doesn’t select a valid quantity then set the quantity to zero and display an error message.
Updated Code
Console.Clear();
Console.WriteLine("\t Purchasing Fruit System\n");
Console.WriteLine("Select Fruit");
Console.WriteLine("A - Apples ");
Console.WriteLine("B - Bananas ");
Console.WriteLine("C - Cherries ");
Console.Write("Enter Your Selection: ");
string menuSelection = null;
double totalPrice = double.MinValue;
int numOfBoxes = int.MinValue;
//Get Fruit Selection
menuSelection = Console.ReadLine();
//Add a switch statement to set Price
switch (menuSelection.ToLower())
{
case "a":
totalPrice = 0.25;
menuSelection = "Apples";
break;
case "b":
totalPrice = 1.60;
menuSelection = "Bananas";
break;
case "c":
totalPrice = 2.50;
menuSelection = "Cherries";
break;
default:
Console.WriteLine("Invalid Selection !");
Console.ReadLine();
return;
}
//Display Menu of Quantitites as Long as a Valid
Console.WriteLine();
Console.WriteLine("How many boxes of {0} do you want ?", menuSelection);
Console.WriteLine("1 - 5 {0}", menuSelection);
Console.WriteLine("2 - 10 {0}", menuSelection);
Console.WriteLine("3 - 15 {0}", menuSelection);
Console.Write("Enter your Selection: ");
//Get Quantity Selection
string value = Console.ReadLine();
if (!int.TryParse (value, out numOfBoxes) || numOfBoxes < 1 || numOfBoxes > 3)
{
Console.WriteLine("Invalid Selection! Quantity is Zero");
Console.WriteLine();
return;
}
//Add a switch statement to set Quantity
switch (numOfBoxes)
{
case 1:
totalPrice *= 5;
break;
case 2:
totalPrice *= 10;
break;
case 3:
totalPrice *= 15;
break;
}
//Display Total for Fruit
if (numOfBoxes <=3)
Console.WriteLine("Quantity is zero Your total is $ 0.00");
else
Console.WriteLine("Total price of {0} boxes of {1} is: {2}", numOfBoxes, menuSelection, totalPrice);
//Pause Display
Console.WriteLine("Press Any Key to Continue.............");
Console.ReadKey();
You are using different variable in switch statement,I think you want menuSelection instead of switchSelection
switch(menuSelection)
{
...
}
Based on your code style I can propose the next code.
Console.Clear();
Console.WriteLine("\t Purchasing Fruit System\n");
Console.WriteLine("Select Fruit");
Console.WriteLine("A - Apples ");
Console.WriteLine("B - Bananas ");
Console.WriteLine("C - Cherries ");
Console.Write("Enter Your Selection: ");
string menuSelection = null;
double totalPrice = double.MinValue;
int numOfBoxes = int.MinValue;
menuSelection = Console.ReadLine ();
switch (menuSelection) {
case "a":
case "A":
totalPrice = 0.25;
menuSelection = "Apples";
break;
case "b":
case "B":
totalPrice = 1.60;
menuSelection = "Bananas";
break;
case "c":
case "C":
totalPrice = 2.50;
menuSelection = "Cherries";
break;
default:
Console.WriteLine ("Invalid Selection !");
return;
}
//Display Menu of Quantitites as Long as a Valid
Console.WriteLine("How many boxes of {0} do you want ?", menuSelection);
Console.WriteLine("1 - 5 {0}", menuSelection);
Console.WriteLine("2 - 10 {0}", menuSelection);
Console.WriteLine("3 - 15 {0}", menuSelection);
Console.Write("Enter your Selection: ");
//Get Quantity Selection
string value = Console.ReadLine ();
if (!int.TryParse (value, out numOfBoxes) || numOfBoxes < 1 || numOfBoxes > 3) {
Console.WriteLine("Invalid Selection !");
numOfBoxes = 0;
}
switch (numOfBoxes) {
case 1:
totalPrice *= 5;
break;
case 2:
totalPrice *= 10;
break;
case 3:
totalPrice *= 15;
break;
}
if(numOfBoxes == 0)
Console.WriteLine("Quantity is zero Your total is $ 0.00");
else
Console.WriteLine("Total price of {0} boxes of {1} is: {2}", numOfBoxes, menuSelection, totalPrice);
Console.ReadLine();
I can't find why cases 2,3 wont let me use else for the category selection but it lets me use it in case 1. Where is it falling apart? What code needs editing?
I fixed the elses I think but I got a new error that I've never seen before control cannot fall through from one case label('case3:') to another. What does this mean?
using System;
class Program
{
enum Numbers { standard = 1, express = 2, same = 3 };
const int A = 1, B = 2;
const int Y = 3, N = 4;
static void Main()
{
double cost, LB;
int Number_of_items;
int myNumbers;
char catagory;
char surcharge = 'Y';
Console.WriteLine("please enter the type of shiping you want");
Console.WriteLine("Enter 1:standard shipping.");
Console.WriteLine("Enter 2:express shipping.");
Console.WriteLine("Enter 3:same day shipping.");
myNumbers = int.Parse(Console.ReadLine());
switch ((Numbers)myNumbers)
{
case Numbers.standard:
Console.WriteLine("thankyou for chooseing standerd shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
catagory = char.Parse(Console.ReadLine());
{
if (catagory == 'A')
{
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 3 * Number_of_items;
Console.Write("is this shipment going to alaska or Hawaii? (Y or N)");
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 2.50;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
}
else
Console.Write("please enter the weight in pounds");
LB = double.Parse(Console.ReadLine());
cost = 1.45 * LB;
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
} surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 2.50;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
break;
case Numbers.express:
Console.WriteLine("thankyou for chooseing Express Shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
catagory = char.Parse(Console.ReadLine());
if (catagory == 'A')
{
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 4 * Number_of_items;
{
Console.Write("is this shipment going to alaska or Hawaii? (Y or N)");
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 5.00;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
}
}
else
{
{
Console.Write("please enter the weight in pounds");
LB = double.Parse(Console.ReadLine());
cost = 2.50 * LB;
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
}
}
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
cost = cost + 5.00;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
break;
case Numbers.same:
Console.WriteLine("thankyou for chooseing Same Day Shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
catagory = char.Parse(Console.ReadLine());
if (catagory == 'A')
{
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 5.50 * Number_of_items;
Console.Write("is this shipment going to alaska or Hawaii? (Y or N)");
surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
{
{
cost = cost + 8.00;
Console.WriteLine("Total cost is {0}.", cost);
}
}
else
{
Console.WriteLine("total cost is {0}.", cost);
}
}
else
{
{
Console.Write("please enter the weight in pounds");
LB = double.Parse(Console.ReadLine());
cost = 3.00 * LB;
surcharge = char.Parse(Console.ReadLine());
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
}
if (surcharge == 'Y')
{
cost = cost + 8.00;
Console.WriteLine("Total cost is {0}.", cost);
}
else
Console.WriteLine("total cost is {0}.", cost);
break;
}
Console.ReadLine();
}//End Main()
}
}
I tried to run your code through Lindent to fix the horrible formatting and it reported unmatched else. You have too many else statements in your code.:
indent: foo.c:93: Error:Unmatched 'else'
indent: foo.c:139: Error:Unmatched 'else'
indent: foo.c:164: Error:Unexpected end of file
(Yes, indent(1) is not intended for C#, but it works surprisingly well on most C-like languages, and in this case has pointed out at least two else statements that aren't properly matched. And don't worry about those specific line numbers -- this routine needs to be properly formatting and broken apart into smaller pieces -- trying to just bodge this together with a few correctly-placed {} isn't the right answer.)
Break apart your gigantic main() routine into smaller functions. (Your code duplicates the Alaska / Hawaii question six times -- that should be a separate routine right there. Maybe all yes / no questions should be handled through one routine: pass in the question and it'll do the prompt and return true or false for you.)
I strongly recommend using braces on your else clauses if you used them on your if clause:
This is fine:
if (foo)
/* statement */
else
/* single statement */
But if you ever need to use braces on the first block, then use them on the else block too:
if (foo) {
/* stuff */
/* more stuff */
} else {
/* use those braces! */
/* you will find reading your code far easier if you do */
}
Good luck.
You've got two problems here. The first is a couple of braces that shouldn't be there. i.e. these:
catagory = char.Parse(Console.ReadLine());
{ // <------- THIS ONE
if (catagory == 'A')
//
// skipped code
//
Console.WriteLine("is this shipment going to alaska or Hawaii? (Y or N)");
} /* <------- THIS ONE */ surcharge = char.Parse(Console.ReadLine());
if (surcharge == 'Y')
The second problem (the one that is causing your control cannot fall through error) is the fact that the break statement for the Numbers.same case is inside a conditioned block of statements (in the else part of your if (catagory == 'A')). This means that it will be executed only when category is different from 'A', and not for every value of your variable. You just have to move the break after the brace.