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;
}
}
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()
{
}
}
}
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.
I have to make a card game like HiLo where you enter your cash amount, you get two cards, and then you bet. if the third randomly generated card is between the other two, you add that money to your total and if its not you lose that money. One thing the code is supposed to do is if you don't like the two cards you are given at the beginning you should be able to enter 0 and they give you new cards. My biggest problem comes from when I enter 0 it gives me two new cards and then asks how much I want to put up and when I enter that number it basically ignores the new bet money and asks me again. essentially i have to write twice the betmoney for it to work, how do I fix that.
using System;
//find how to print dollar signs
class MainClass {
public static void Main (string[] args) {
var rnd = new Random();
int card1, card2, card3;
int playermoney = 0;
int betmoney = 0;
string exit = "";
Console.WriteLine("HiLo Card Game");
Console.Write("Enter the starting cash amount: $");
playermoney = Convert.ToInt32(Console.ReadLine());
while(exit!="n"){
card1 = rnd.Next(1,15);
card2 = rnd.Next(1,15);
Console.WriteLine("Cash balance is ${0}",playermoney);
Console.WriteLine("{0} - {1}", card1, card2);
Console.Write("The amount you want to bet? ");
betmoney = Convert.ToInt32(Console.ReadLine());
if (betmoney>=0){
if (betmoney == 0){
Console.WriteLine("Cash balance is ${0}",playermoney);
Console.WriteLine("{0} - {1}", rnd.Next(1,15), rnd.Next(1,15));
Console.Write("The amount you want to bet? ");
betmoney = Convert.ToInt32(Console.ReadLine());
continue;
}//end if 0
card3 = rnd.Next(1,15);
Console.WriteLine("Your card is a {0}", card3);
if(card1<card2){
if((card3>card1 && card3<card2)){
playermoney = playermoney+betmoney;
Console.WriteLine("WINNER! New Balance is {0}", playermoney);
}//end winner if
else{
playermoney = playermoney-betmoney;
Console.WriteLine("LOSER! New Balance is {0}", playermoney);
if (playermoney<0){
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}//end negative if
}//end else loser
}
if (card1>card2){
if(card3>card2 && card3<card1){
playermoney = playermoney+betmoney;
Console.WriteLine("WINNER! New Balance is {0}", playermoney);
}
else{
playermoney = playermoney-betmoney;
Console.WriteLine("LOSER! New Balance is {0}", playermoney);
if (playermoney<0){
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}//end negative if
}//end else loser
}
}
else{
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}
Console.Write("Play Again? <y/n> ");
exit = Console.ReadLine();
Console.Clear();
}
}
}
I think what you want to do is continue right away if the betAmount is 0 (or less than zero), rather than trying to pick new cards again inside the main loop:
if (betMoney < 1) continue;
Some other thoughts:
Additionally, you should use int.TryParse to parse the integer input because Convert.ToInt32 will throw an exception if the input is not a valid integer. This way we can use TryParse as an if condition and continue to ask them for a valid number.
Random should almost always be declared as a class field rather than a local variable. In this case it doesn't matter, but it's a good habit to get into.
We can use Math.Max and Math.Min to determine which of the two random cards are the largest and smallest, to avoid the repetitive code (the code in the if (card1 > card2) block is repeated for card2 > card1)
We can use Math.Abs to determine the absolute value of the difference of card1 and card2, so if they are the same card or are sequential, we can just continue the loop (there is no chance to win in those cases).
We can move the Console.Clear inside the loop so after they enter the initial playerMoney amount, we always see the same screen while playing.
We can use Console.ReadKey() to get a single key from the user (for y/n), and then use the .Key property to determine if it's an n or N.
Here's some code with these ideas implemented:
private static Random rnd = new Random();
static void Main()
{
Console.WriteLine("HiLo Card Game");
Console.WriteLine("--------------");
Console.Write("Enter the starting cash amount: $");
int playerMoney;
while (!int.TryParse(Console.ReadLine(), out playerMoney) ||
playerMoney < 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Please enter a positive number for cash amount: $");
Console.ResetColor();
}
while (true)
{
// Draw two random cards
int card1 = rnd.Next(1, 15);
int card2 = rnd.Next(1, 15);
// Start the loop again if there is not at least
// one card available between card1 and card2
if (Math.Abs(card1 - card2) < 2) continue;
// Determine the min and max of the two random cards
var minCard = Math.Min(card1, card2);
var maxCard = Math.Max(card1, card2);
Console.Clear();
Console.WriteLine("HiLo Card Game");
Console.WriteLine("--------------");
Console.WriteLine("Cash balance is: ${0}", playerMoney);
Console.WriteLine("{0} - {1}", minCard, maxCard);
Console.Write("Enter the amount you want to bet: $");
int betMoney;
while (!int.TryParse(Console.ReadLine(), out betMoney))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Please enter a valid number for bet amount: $");
Console.ResetColor();
}
// If the bet amount is negative or 0, restart
// the loop so they can get new cards
if (betMoney < 1) continue;
// Draw a card for the player
int playerCard = rnd.Next(1, 15);
Console.WriteLine("Your card is: {0}", playerCard);
// If the players card is between the random cards, they win
if (playerCard < maxCard && playerCard > minCard)
{
playerMoney += betMoney;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("WINNER! New Balance is ${0}", playerMoney);
Console.ResetColor();
}
else
{
playerMoney -= betMoney;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("LOSER! New Balance is ${0}", playerMoney);
Console.ResetColor();
if (playerMoney <= 0)
{
Console.WriteLine("--------------");
Console.Write("Game over. Press any key to exit...");
Console.ReadKey();
break;
}
}
Console.Write("Play Again? <y/n>: ");
if (Console.ReadKey().Key == ConsoleKey.N) break;
}
}
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?
Here is my loop that asks for the group number then the donation. I'm wondering how to count the number of donations to find the average for each group.
using System;
public class TotalPurchase
{
public static void Main()
{
double total4 = 0;
double total5 = 0;
double total6 = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
break;
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4 += donation4;
break;
case 5:
double donation5;
string inputString5;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString5 = Console.ReadLine();
donation5 = Convert.ToDouble(inputString5);
total5 += donation5;
break;
case 6:
double donation6;
string inputString6;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString6 = Console.ReadLine();
donation6 = Convert.ToDouble(inputString6);
total6 += donation6;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Grade 4 total is {0}", total4.ToString("C"));
Console.WriteLine("Grade 5 total is {0}", total5.ToString("C"));
Console.WriteLine("Grade 6 total is {0}", total6.ToString("C"));
}
}
Any help would be appreciated.
Not sure if I fully understand your question -- but you could just add a simple counter for each group:
int donations4 = 0;
int donations5 = 0;
int donations6 = 0;
And then increment that counter in each of your switch cases, ex:
switch(myInt)
{
case 4:
...
donations4++;
break;
case 5:
...
donations5++;
break;
case 6:
...
donations6++;
break;
}
Then when you're done - simply do the math to find the average.
Although this is probably the simplest way, a better way would be to treat each group as its own object, and have the object internally track the # of donations, as well as the sum and average.
-- Dan
using System;
public class TotalPurchase
{
public static void Main()
{
double total4 = 0;
double total5 = 0;
double total6 = 0;
int numberOfInputForTotal4 = 0;
int numberOfInputForTotal5 = 0;
int numberOfInputForTotal6 = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
break;
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4 += donation4;
numberOfInputForTotal4++;
break;
case 5:
double donation5;
string inputString5;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString5 = Console.ReadLine();
donation5 = Convert.ToDouble(inputString5);
total5 += donation5;
numberOfInputForTotal5++;
break;
case 6:
double donation6;
string inputString6;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString6 = Console.ReadLine();
donation6 = Convert.ToDouble(inputString6);
total6 += donation6;
numberOfInputForTotal6++;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Grade 4 total is {0}", total4.ToString("C"));
Console.WriteLine("Grade 5 total is {0}", total5.ToString("C"));
Console.WriteLine("Grade 6 total is {0}", total6.ToString("C"));
Console.WriteLine("Grade 4 average is {0}", (total4 / numberOfInputForTotal4).ToString("C"));
Console.WriteLine("Grade 5 average is {0}", (total5 / numberOfInputForTotal5).ToString("C"));
Console.WriteLine("Grade 6 average is {0}", (total6 / numberOfInputForTotal6).ToString("C"));
}
}
As you can see, there are 3 extra variables (one for each group) that can be used to figure out the number of inputs provided. Using that you can divide the total for each group by the number of input in each group separately.
Just declare count for each group as well as total and increment in the case statement:
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4 += donation4;
count4++; // HERE!!!!
break;
Alternatively, you can use List<int> which will calculate your average as well:
List<int> list4 = new List<int>();
and
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
list4.Add(donation4);
break;
and
Console.WriteLine(list4.Average());
Just keep track of the count yourself with another variable. count4, count5, etc.
For bonus points in your homework assignment:
1) Sanitize your group number input - ie check to see if the user typed in a valid number.
2) Don't call the variable myInt. Call it groupNum, or something that describes the function, not the implementation of the variable.
3) Use an array for donation totals and counts
ie,
int[] donationCount= new int[MAX_GROUP+1]; // figure out yourself why the +1
int[] donationTotal= new int[MAX_GROUP+1];
// initialize donationCount and donationTotal here
then in your loop (don't even need switch):
++donationCount[groupNum];
donationTotal[groupNum] += donationAmount; // did you notice that you moved the reading of donationAmount out of the switch?
I would go with changing your doubles to List and using the Sum() and Average() methods on your Lists at the end. Your code would look like this after this change.
using System;
using System.Collections.Generic;
using System.Linq;
public class TotalPurchase
{
public static void Main()
{
List<double> total4 = new List<double>();
List<double> total5 = new List<double>();
List<double> total6 = new List<double>();
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
break;
case 4:
double donation4;
string inputString4;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString4 = Console.ReadLine();
donation4 = Convert.ToDouble(inputString4);
total4.Add(donation4);
break;
case 5:
double donation5;
string inputString5;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString5 = Console.ReadLine();
donation5 = Convert.ToDouble(inputString5);
total5.Add(donation5);
break;
case 6:
double donation6;
string inputString6;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString6 = Console.ReadLine();
donation6 = Convert.ToDouble(inputString6);
total6.Add(donation6);
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
if(total4.Count > 0)
Console.WriteLine("Grade 4 total is {0}; Average {1}", total4.Sum().ToString("C"), total4.Average().ToString("C"));
if(total5.Count >0)
Console.WriteLine("Grade 5 total is {0}; Average {1}", total5.Sum().ToString("C"), total5.Average().ToString("C"));
if (total6.Count > 0)
Console.WriteLine("Grade 6 total is {0}; Average {1}", total6.Sum().ToString("C"), total6.Average().ToString("C"));
}
}