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
Related
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 last year.
Improve this question
I try to calculate the total collective age of my passengers in calc_total_age() this works before I add a passenger and writes out "0". However when I add a passenger I get NullReferenceException, I have tried different things but I just can't wrap my head around what I'm doing. I need a little shove in the right direction and maybe and explanation of what the he** I am doing and I don't know what my GetAge() does either really I have tried to call it but it doesn't seem to work.
This is all my code:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program {
public static void Main (string[] args) {
//Console.Clear();
Console.WriteLine("Hi, welcome to the Buss-Simulator!");
Console.ReadKey();
var mybus = new Bus();
mybus.Run();
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Bus {
public int total_passengers = 0;
public Passenger[] info_passengers;
public int totalAge = 0;
public int totalSeats = 25;
public void Run()
{
info_passengers = new Passenger[25];
string [] menu = new string[]{"1. Pick up passenger.", "2. Show who's on the bus.", "3. Calculate total age of passengers"};
int MenuSelect = 0;
while (true)
{
Console.Clear();
Console.WriteLine("What do you want to do?");
Console.WriteLine();
Console.CursorVisible = false;
if (MenuSelect == 0)
{
Console.WriteLine(menu[0] + " ⭅");
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 1)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1] + " ⭅");
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 2)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2] + " ⭅");
}
var keyPressed = Console.ReadKey();
if(keyPressed.Key == ConsoleKey.DownArrow && MenuSelect != menu.Length -1)
{
MenuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && MenuSelect >= 1)
{
MenuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (MenuSelect)
{
case 0:
add_passengers();
break;
case 1:
print_passengers();
break;
case 2:
calc_total_age();
break;
}
}
}
}
public void add_passengers()
{
if (total_passengers == 25)
{
Console.WriteLine("\nBus is full!");
System.Threading.Thread.Sleep(2000);
return;
}
try
{
Console.WriteLine("\nType the name, age & gender of your passenger.");
Console.Write("\nName: ");
string name = Console.ReadLine();
Console.Write("\nAge: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("\nGender: ");
string gender = Console.ReadLine();
Passenger passenger = new Passenger(aName: name, aAge: age, aGender: gender);
Array.Resize(ref info_passengers, info_passengers.Length + 1);
info_passengers[info_passengers.Length - 1] = passenger;
}
catch (Exception e)
{
Console.WriteLine("\nFollow instructions.");
System.Threading.Thread.Sleep(2000);
return;
}
total_passengers++;
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
System.Threading.Thread.Sleep(2000);
return;
}
public void print_passengers()
{
Console.WriteLine();
foreach (var i in info_passengers)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
public void calc_total_age()
{
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
Console.WriteLine(totalAge);
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Passenger{
public string name;
public int age;
public string gender;
public Passenger(string aName, int aAge, string aGender)
{
name = aName;
age = aAge;
gender = aGender;
}
public override string ToString()
{
return string.Format($"This is {name}, {gender}, {age} years old.");
}
public int GetAge()
{
return age;
}
}
you don't need to resize info_passengers array since it is enough for total passangers. When you add an extra array cell, you add a passanger to the end of arry, but you still have the empty cells in the beginnig of array with null that are causing the exception.
so remove this code
Array.Resize(ref info_passengers, info_passengers.Length + 1);
and fix this
total_passengers++;
info_passengers[ total_passengers-1] = passenger;
and don't forget to remove total_passengers++; from here
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
and add totalAge=0 in calc_total_age
public void calc_total_age()
{
totalAge=0;
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
and it is not a very good idea to hide errors in your catch blok. I would make it
catch (Exception e)
{
Console.WriteLine("\n Error!!! " + e.Message);
System.Threading.Thread.Sleep(2000);
return;
}
The answer to this one is very simple!
You declare:
public Passenger[] info_passengers;
This actually creates a pointer to a Passenger array, which (like all pointers) is initially null. It does not create the actual array itself.
When your code comes to call:
Array.Resize(ref info_passengers, info_passengers.Length + 1);
the method Resize expects the array parameter to point to an array. However, info_passengers is still null. So you get the exception.
I think all you need to do is to initialise info_passengers to an new empty array, like this:
public Passenger[] info_passengers = new Passenger[]();
and then I think it'll all work.
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
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.
I'm doing an exercise of converting fahrenheits to celsius , my question is , how can i say to the program to not accept letters when the user inputs anything? (which is supposed to be only numbers).
My code is this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FirstCsharpProgram
{
class Program
{
static void Main(string[] args)
{
//declaring the first temperature needed
float originalFahrenheit;
float cels;
//Input fehrenheit degrees from the user
Console.Write("Enter temperature (Fahrenheit): ");
originalFahrenheit = float.Parse(Console.ReadLine());
cels = (((originalFahrenheit - 32) /9) * 5);
Console.Write(originalFahrenheit + " fahrenheit = " + cels);
Console.Write(" celsius");
Console.Write("");
}
}
}
I would like to have the next piece of code in my program as the exercise intends to start with it
Console.Write("Enter temperature (Fahrenheit): ");
originalFahrenheit = float.Parse(Console.ReadLine());
If you could help me proceeding with that piece of code i would be grateful
Thank you
I would do it this way:
static float ReadFloatFromConsole()
{
float number;
while (!float.TryParse(Console.ReadLine(), out number))
{
Console.WriteLine("Invalid number, please try again");
}
return number;
}
if(!float.TryParse(Console.ReadLine(), out originalFahrenheit)) //Parse fail
{
//Your error message
return; //Exit program
}
I made a dice game and just a few moments ago asked for a solution here, which i got. it made a new problem and in which i cant seem to find a answer.
Heres the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Noppapeli
{
class Program
{
static void Main(string[] args)
{
int pyöräytys;
int satunnainen;
int luku = 0;
Random noppa = new Random((int)DateTime.Now.Ticks);
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
Console.WriteLine("Haettava numero on: " + pyöräytys);
Console.ReadLine();
do
{
luku++;
satunnainen = noppa.Next(1, 7);
Console.WriteLine("numero on: " + satunnainen);
if (satunnainen == pyöräytys)
{
satunnainen = pyöräytys;
}
} while (pyöräytys != satunnainen);
Console.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
Console.WriteLine("Haettu numero: " + pyöräytys);
Console.WriteLine("Pyöräytetty numero: " + satunnainen);
Console.Write("Kesti " + luku + " Nopan pyöräytystä saada tulos!");
Console.ReadLine();
}
}
}
The problem is that int.TryParse(Console.ReadLine(),out pyöräytys); needs to only take values between 1-6. now if I put a 7 in there the game is on a loop to find a 7 from a D6.
Is there a easy solution or should i just make the dices bigger.
You simply need to add some kind of loop to ensure the value is valid and continue looping until a valid value is provided.
pyöräytys = -1; // Set to invalid to trigger loop
while (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
if (pyöräytys < 1 || pyöräytys > 6)
{
Console.WriteLine("Invalid value, must be 1-6"); // Error message
}
}
Just verify the input value is between 1 and 6:
bool valid;
while (!valid)
{
Console.WriteLine("Anna arvaus");
int.TryParse(Console.ReadLine(),out pyöräytys);
valid = (pyöräytys > 0 && pyöräytys <= 6);
}