I'm working on making a running total for a coin calculator we're creating for a school project. It's a C# program running in Visual Studio 2019. Currently, I have it adding total change for a single instance, but I need to add a running total that shows before you end the program.
I've tried looking online, but I cant seem to find code that would fit into what I am making. I'm a beginner with C#, so all my ideas have fallen short. Here is my code; hopefully someone can help me out. (Note that the running total should go into the while statement when the user enters N.)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace CalcChange
{
class Program
{
static void Main(string[] args)
{
string choice;
int q, d, n, p, hd;
int totchange, totcents, dollars, cents;
Console.WriteLine("Welcome to the Change Calculator");
Console.Write("Do you have change? (y/n): ");
choice = Console.ReadLine();
while (choice.Equals("Y", StringComparison.CurrentCultureIgnoreCase))
{
hd = getCoin("Helf Dollars");
q = getCoin("Quarters");
d = getCoin("Dimes");
n = getCoin("Nickels");
p = getCoin("Pennies");
totcents = (hd * 50) + (q * 25) + (d * 10) + (n * 5) + p;
Console.WriteLine("\nYou have " + totcents + " Cents.");
dollars = totcents / 100;
cents = totcents % 100;
Console.WriteLine("Which is " + dollars + " dollars and "
+ cents + " cents.\n");
Console.WriteLine("I'm in the loop!");
Console.Write("Do you have more change? (y/n): ");
choice = Console.ReadLine();
}
while (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
{
}
if (Debugger.IsAttached)
{
Console.Write("Press any key to Continue...");
Console.ReadKey();
}
} //end of main
static int getCoin(string cointype)
{
int ccount;
do
{
try
{
Console.Write("How many " + cointype + " do you have?");
ccount = int.Parse(Console.ReadLine());
if (ccount < 0)
{
Console.WriteLine("Coin amounts cannot be negative, please re-enter a valid amount.");
}
}
catch (Exception ex)
{
Console.WriteLine("Illegal input: " + ex.Message + " please re-enter a valid amount.");
ccount = -1;
}
} while (ccount < 0);
return ccount;
}
} //end of class
}
Well just keep a variable that will sum all iterations
For example:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace CalcChange
{
class Program
{
static void Main(string[] args)
{
string choice;
int q, d, n, p, hd;
int totchange, totcents, dollars, cents;
int grandTotal = 0;
Console.WriteLine("Welcome to the Change Calculator");
Console.Write("Do you have change? (y/n): ");
choice = Console.ReadLine();
while (choice.Equals("Y", StringComparison.CurrentCultureIgnoreCase))
{
hd = getCoin("Helf Dollars");
q = getCoin("Quarters");
d = getCoin("Dimes");
n = getCoin("Nickels");
p = getCoin("Pennies");
totcents = (hd * 50) + (q * 25) + (d * 10) + (n * 5) + p;
Console.WriteLine("\nYou have " + totcents + " Cents.");
// once the user puts his change add the total cents to the grandtotal
// variable
grandTotal += totcents;
dollars = totcents / 100;
cents = totcents % 100;
Console.WriteLine("Which is " + dollars + " dollars and "
+ cents + " cents.\n");
Console.WriteLine("I'm in the loop!");
Console.Write("Do you have more change? (y/n): ");
choice = Console.ReadLine();
}
while (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
{
}
// here print the value
Console.WriteLine($"You have a total of {grandTotal / 100} dollars and {grandTotal % 100} cents");
if (Debugger.IsAttached)
{
Console.Write("Press any key to Continue...");
Console.ReadKey();
}
} //end of main
static int getCoin(string cointype)
{
int ccount;
do
{
try
{
Console.Write("How many " + cointype + " do you have?");
ccount = int.Parse(Console.ReadLine());
if (ccount < 0)
{
Console.WriteLine("Coin amounts cannot be negative, please re-enter a valid amount.");
}
}
catch (Exception ex)
{
Console.WriteLine("Illegal input: " + ex.Message + " please re-enter a valid amount.");
ccount = -1;
}
} while (ccount < 0);
return ccount;
}
} //end of class
}
I added some comments in the code for more clarity
Hope this helps
Related
Example code:
//money deposit
Console.Write("Enter said amount of money: ");
moneyres = Convert.ToDouble(Console.ReadLine());
if (moneyres < ticket)
{
double dif = ticket - moneyres;
Console.Write("Oh, sorry you are " + dif + " dollar(s) sort.\nPlease enter more money so you can purchase the ticket: ");
double m2 = Convert.ToDouble(Console.ReadLine());
double m3 = dif - m2;
while (m3 > 0)
{
Console.Write("Oh, sorry you are " + m3 + " dollar(s) sort.\nPlease enter more money so you can purchase the ticket: ");
}
}
else if (moneyres > ticket)
{
change = moneyres - ticket;
Console.WriteLine("So your change is: " + change + " dollar(s).\nHere you go. Have fun!");
}
else
{
Console.WriteLine("Here you go. Have fun!");
}
So let's say the ticket is 10 bucks and someone puts 5. Then the difference is going to be 5. Then lets say he adds 2 more.
How can I do a loop till the amount hits 0? (I am new to coding btw).
You can do all of this in a while loop.
double totalValue = 0.0;
while(totalValue < ticket)
{
Console.Write("Enter said amount of money: ");
moneyres = Convert.ToDouble(Console.ReadLine());
totalValue += moneyres;
if (totalValue > ticket)
{
// Enough
}
else
{
// Not enough
}
}
You should look into a while loop. Something like while(UserInput < ticket). UserInput in this case is the amount that the user pays.
So I did this. Thanks a lot for the suggestions!
double tot = 0.0;
while (tot < ticket)
{
string sp = "Enter money: ";
Console.Write(sp);
moneyres = Convert.ToDouble(Console.ReadLine());
tot += moneyres;
if (tot > ticket)
{
change = tot - ticket;
Console.WriteLine("Alright here is your change. That's " + change + " dolars.And
here is your ticket!\nEnjoy your ride!");
}
else if (tot==ticket)
{
Console.WriteLine("That's just perfect! Here you go!\nEnjoy your ride!");
}
else
{
Console.WriteLine("You did not enter enough money.");
}
}
Console.ReadKey();
I am very new to C# and I was wondering how I can validate user input before placing their input in my array. I am trying to create a console application to create a vertical and horizontal histogram, made of stars. So I am asking the user for 8 numbers between 1-10 and printing their results onto the screen as a histogram.
I need help with 3 things:
1. How can I make it so that they can only enter numbers into the menu and the array?
2. I'm not sure how to display the histogram vertically, I've done the horizontal one and can't figure out how to make it vertical.
3. Also, I'd like to have labels going down the histograms. E.g
1 **** (Number of stars user selected)
2 ****** (Number of stars user selected)
3 ***** (Number of stars user selected)
4 * etc.
Would greatly appreciate any help! Thank you so much in advance. :)
Here is what I've got so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class Program
{
static void Main(string[] args)
{
clsMainMenu MainMenu = new clsMainMenu();
ConsoleKeyInfo ConsoleKeyPressed;
do
{
MainMenu.DisplayMenu();
ConsoleKeyPressed = Console.ReadKey(false);
Console.WriteLine();
switch (ConsoleKeyPressed.KeyChar.ToString())
{
case "1":
clsHistogram Histogram = new clsHistogram();
Histogram.CreateHorizontalHistogram();
break;
case "2":
clsHistogram HistogramV = new clsHistogram();
HistogramV.CreateVerticalHistogram();
break;
}
} while (ConsoleKeyPressed.Key != ConsoleKey.Escape);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsMainMenu
{
public void DisplayMenu()
{
Console.WriteLine("1. Create a Horizontal Histogram.");
Console.WriteLine("2. Create a Vertical Histogram.");
Console.WriteLine("Press Esc to exit the Program.");
Console.WriteLine("..................................");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_3A
{
class clsHistogram
{
string strNumberChosen = "";
public void CreateHorizontalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" *");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Horizontal Array.
}
public void CreateVerticalHistogram()
{
Console.WriteLine("Please enter a number between 1 and 10:");
int[] intHistogramArray = new int[8];
for (int intCounter = 0; intCounter < 8; intCounter++)
{
Console.WriteLine("Enter number " + (intCounter + 1) + " :");
strNumberChosen = Console.ReadLine(); // Need Data Validation Here.
} // Populating Array.
Console.WriteLine("Your Histogram looks like this: ");
for (int intcounter = 0; intcounter < 8; intcounter++)
{
int intStarPlot = intHistogramArray[intcounter];
while (intStarPlot > 0)
{
Console.Write(" * \n");
intStarPlot -= 1;
}
Console.WriteLine();
} // Display a Vertical Array.
}
}
}
Here is an example of code that would use the int.TryParse() method to evaluate the entered data.
private static readonly char star = '*';
private static readonly uint minValue = 1;
private static readonly int maxValue = 10;
private static void CreateHorizontalHistogram()
{
var limits = "a number between " + minValue + " and " + maxValue + ": ";
Console.WriteLine("Please enter " + limits);
var list = new List<int>();
do
{
var message = string.Empty;
bool isNumber = false;
bool isRightSize = false;
int output;
do
{
var input = Console.ReadLine();
isNumber = int.TryParse(input, out output);
if(isNumber)
{
isRightSize = minValue <= output && output <= maxValue;
message = isRightSize ? "That will do: " : "Try again - value is not " + limits + output;
}
else
{
message = "Try again - " + input + " is not a Number";
}
Console.WriteLine(message);
}while(!isNumber || !isRightSize);
Console.WriteLine("Entered number at position" + (list.Count + 1) + " : " + output);
list.Add(output);
}while(list.Count <= 8);
Console.WriteLine("Your Histogram looks like this: ");
foreach(var value in list)
{
Console.WriteLine(string.Empty.PadRight(value, star));
}
Console.WriteLine("Or like this with LINQ");
list.ForEach(n => Console.WriteLine(string.Empty.PadRight(n, star)));
}
NOTE:
I used a List<int> of integers instead of an array int[]...my personal preference.
I changed the way the diagram was created. My version is a bit less verbose.
I also added an additional example of how you could create the diagram using LINQ-- always looks good.
Please, let me know if you have any questions.
This question already has answers here:
How to loop a Console App
(6 answers)
Closed 6 years ago.
I wanted to try how the if conditional works so I created this code almost by myself. I also had problems with random into int.
Here's my code:
using System;
namespace Bigger_Smaller_Equal
{
class Program
{
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
Console.WriteLine("Press Any Key to exit.");
Console.ReadLine();
}
}
}
How to make the console stop, so it will allow me to enter another number?
Basically:
I write a number it tells me if its smaller bigger or equal to number which was randomly generated
After I press enter instead of closing the console the number will be generated again and I can write new number and so on.
Here's an example using goto, although it is not recommended for more complex applications as you could end up creating endless loops. Feel free to try it out
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
again:
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
repeat:
Console.WriteLine("Play again? (Y/N)");
string ans = Console.ReadLine();
switch (ans.ToUpper())
{
case "Y": goto again; break;
case "N": break; //continue
default: goto repeat; break;
}
}
You can use console.ReadKey() insted of using console.ReadLine().
console.ReadLine() wait for input set of character thats why you console window is apperre there after pressing any key.
You can use "do while" or "while" operator.If you dont want to use while(true) , you can use this diffirent way. I mean that when user enter 0 or -1 this system can stop. while()
bool repeat = true;
do
{
Console.WriteLine("Enter value ");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num!=0)
// bla bla bla.
else
repeat = false;
}while (repeat);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TipCalculator
{
class Program
{
static void Main(string[] args)
{
string answer;
float totalPrice;
Console.WriteLine("Would you like to calculate a tip?");
answer = Console.ReadLine();
if (answer == "yes")
{
Console.WriteLine("Please enter the total price of your meal");
totalPrice = float.Parse(Console.ReadLine());
if (totalPrice >= 20.00)
TipCalculator.over20(totalPrice);
else if (totalPrice < 20)
TipCalculator.under20(totalPrice);
else Console.WriteLine("Error. Please type in the value of the bill again");
}
else if (answer == "no")
Console.WriteLine("Please run this again when you wish to calculate a tip.");
else
Console.WriteLine("Error. Please type in \"yes\" or \"no\"");
Console.ReadLine();
}
}
public class TipCalculator
{
public static string over20(float bill)
{
float tip, totalBill;
tip = (bill * (float)1.2);
totalBill = (tip + bill);
return "Very good. The total tip to be paid is " + tip + " and this will cost " + totalBill + "in total.";
}
public static string under20(float bill)
{
float tip, totalBill;
tip = (bill * (float)1.1);
totalBill = (tip + bill);
return "Very good. The total tip to be paid is " + tip + " and this will cost " + totalBill + "in total.";
}
}
}
When I try to run this code no error is displayed however the message starting with "Very good" does not display in the over20 or under20 message. Thanks in advance!
The issue is that you are returning string from methods over20 and under20, but you are not using them anywhere. Update the part of your code to print the output using Console.WriteLine:
if (totalPrice >= 20.00)
Console.WriteLine(TipCalculator.over20(totalPrice));
else if (totalPrice < 20)
Console.WriteLine(TipCalculator.under20(totalPrice));
else Console.WriteLine("Error. Please type in the value of the bill again");
Working example
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitSum
{
class Program
{
static void Main(string[] args)
{
int num, sum = 0, r;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
while (num != 0)
{
r = num % 10;
num = num / 10;
sum = sum + r;
}
Console.WriteLine("The sum of the digits in the number: " + num + " is " + sum);
Console.ReadLine();
}
}
}
This program will take a user input number (eg. 123) and will return (The sum of the digits in the number: 0 is 6).
I need to know how I can change my code so that the program will output (The sum of the digits in the number: 123 is 6).
EDIT: Thanks for all the input everybody. I actually managed to figure it out the night I posted the problem but I'm sure someone else could use the help. I ended up keeping the while loop and saved the value of num by using a secondary variable before the loop occurs.
I realized afterwards that a while loop was probably the most convoluted way I could have solved the problem but I am glad I did because it taught me to re-evaluate the way I approach a code if I have a problem.
This might help.
static void Main()
{
Console.WriteLine("Enter a Number : ");
string input = Console.ReadLine();
int num, sum = 0;
if (int.TryParse(input, out num))
{
for (; num > 0; num = num / 10)
{
sum = sum + num % 10;
}
Console.WriteLine("The sum of the digits in the number: {0} is {1}", input, sum);
}
else { Console.WriteLine("Invalid number format."); }
Console.ReadKey();
}
you are changing num.
take a copy of it.
after
num = int.Parse(Console.ReadLine());
safe a copy like
int numOutput = num;
and print it like
Console.WriteLine("The sum of the digits in the number: " + numOutput + " is " + sum);
and another hint. When you use string outputs you can do this for better readability:
Console.WriteLine("The sum of the digits in the number: {0} is {1}", numOutput, sum);
Make a copy of num so that you can still print it out at the end even if you needed to count it down during the summation:
num = int.Parse(Console.ReadLine());
int originalNum = num;
// …
Console.WriteLine("The sum of the digits in the number: " + originalNum + " is " + sum);
This is happening because you are modifyingnum in your while loop. You can store num's value in another temporary variable, say int temp = num, just before the while loop. Then, when you output, replace the num with temp in
Console.WriteLine("The sum of the digits in the number: " + num + " is " + sum);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitSum
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a Number : ");
var num = Console.ReadLine();
var sum = num.Select(c => int.Parse(c.ToString())).Sum();
Console.WriteLine("The sum of the digits in the number: " + num + " is " + sum);
Console.ReadLine();
}
}
}